package com.bootdo.wx.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaShopAfterSaleService;
import cn.binarywang.wx.miniapp.api.WxMaShopOrderService;
import cn.binarywang.wx.miniapp.api.WxMaShopSpuService;
import cn.binarywang.wx.miniapp.api.impl.WxMaShopAfterSaleServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaShopOrderServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaShopSpuServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.shop.WxMaShopAfterSaleProductInfo;
import cn.binarywang.wx.miniapp.bean.shop.WxMaShopDeliveryItem;
import cn.binarywang.wx.miniapp.bean.shop.request.WxMaShopAddAfterSaleRequest;
import cn.binarywang.wx.miniapp.bean.shop.request.WxMaShopOrderPayRequest;
import cn.binarywang.wx.miniapp.bean.shop.request.WxMaShopOrderRecieveRequest;
import cn.binarywang.wx.miniapp.bean.shop.request.WxMaShopOrderSendRequest;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaShopBaseResponse;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.bootdo.common.config.Constant;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.OrderExcelUtils;
import com.bootdo.system.dao.UserDao;
import com.bootdo.wx.api.ApiWeChatPayController;
import com.bootdo.wx.constant.Constants;
import com.bootdo.wx.dao.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.OrderOrderService;
import com.bootdo.wx.service.OrderTeamMoneyService;
import com.bootdo.wx.service.WeChatPayService;
import com.github.pagehelper.PageInfo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.n3r.idworker.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static com.bootdo.common.utils.ShiroUtils.getUserId;

@Service
public class OrderOrderServiceImpl implements OrderOrderService {
	@Autowired
	private OrderOrderDao orderOrderDao;
	@Autowired
	private OrderShippingDao orderShippingDao;
	@Autowired
	private MemberUserDao memberUserDao;
	@Autowired
	private MemberAddressDao memberAddressDao;
	@Autowired
	private GoodsProductDao goodsProductDao;
	@Autowired
	private OrderDetailDao orderDetailDao;
	@Autowired
	private CmsContentDao cmsContentDao;
	@Autowired
	private OrderComDao orderComDao;
	@Autowired
	private MemberCartDao memberCartDao;
	@Autowired
	private GoodsGoodsDao goodsGoodsDao;
	@Autowired
	private OrderComentDao orderComentDao;
	@Autowired
	private MemberCouponDao memberCouponDao;
	@Autowired
	private GoodsSpikeDao goodsSpikeDao;
	@Autowired
	private OrderTeamMoneyDao orderTeamMoneyDao;
	@Autowired
	private OrderModifyDao orderModifyDao;
	@Autowired
	private OrderTeamMoneyService orderTeamMoneyService;
	/*
	 * @Autowired private GoodsNineDao goodsNineDao;
	 */
	@Autowired
	private GoodsBargainDao goodsBargainDao;
	@Autowired
	private OrderBargainDao orderBargainDao;
	@Autowired
	private OrderBargainUserDao orderBargainUserDao;
	@Autowired
	private ShopExpressMessageDao shopExpressMessageDao;
	@Autowired
	private ShopExpressCodeDao shopExpressCodeDao;
	@Autowired
	private ShopExpressDetailsDao shopExpressDetailsDao;
	@Autowired
	private OrderExcelRecodeDao orderExcelRecodeDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private OrderBackDao orderBackDao;
	@Autowired
	private MemberPriceDao memberPriceDao;
	@Autowired
	private MemberStockDao memberStockDao;
	@Autowired
	private SalesCouponDao salesCouponDao;
	@Autowired
	private GoodsTeamDao goodsTeamDao;
	@Autowired
	private OrderTeamDao orderTeamDao;
	@Autowired
	private OrderTeamUserDao orderTeamUserDao;
	@Autowired
	private GoodsUpgradeDao goodsUpgradeDao;
	/*
	 * @Autowired private MemberUpgradeService memberUpgradeService;
	 * 
	 * @Autowired private MemberLevelChangeDao memberLevelChangeDao;
	 */
	@Autowired
	private WeChatPayService weChatPayService;
	@Autowired
	private OrderSetDao orderSetDao;
	@Autowired
	private ShopExpressMoneyDao shopExpressMoneyDao;
	@Autowired
	private MemberLevelChangeDao memberLevelChangeDao;

	@Autowired
	private WxMaProperties properties;
	@Autowired
	private CmsNoticeDao cmsNoticeDao;
	@Autowired
	private ApiWeChatPayController apiWeChatPayController;


	@Override
	public OrderOrderDO get(String id) {
		return orderOrderDao.get(id);
	}

	@Override
	public List<OrderOrderDO> list(Map<String, Object> map) {
		return orderOrderDao.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return orderOrderDao.count(map);
	}

	@Override
	public int save(OrderOrderDO orderOrder) {
		return orderOrderDao.save(orderOrder);
	}

	@Override
	public int update(OrderOrderDO orderOrder) {
		return orderOrderDao.update(orderOrder);
	}

	@Override
	public int remove(String id) {
		return orderOrderDao.remove(id);
	}

	@Override
	public int batchRemove(String[] ids) {
		return orderOrderDao.batchRemove(ids);
	}

	public static AtomicInteger race = new AtomicInteger(0);

	/* 购物车添加订单 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addCartOrder(Map<String, Object> paramMap) {
		List<Map<String,Object>> cartList = (List<Map<String,Object>>) paramMap.get("cartList"); // 商品集合
		String userId = paramMap.get("userId").toString(); // 用户id
		int postType = Integer.valueOf(paramMap.get("postType").toString()); // 配送方式：0：自提，1：快递
		int payType = Integer.valueOf(paramMap.get("payType").toString()); // 0：微信支付，1：支付宝支付,
		//int isPostInsurance = Integer.valueOf(paramMap.get("isPostInsurance").toString());																// 2余额支付
		//String buyerMsg = paramMap.get("buyerMsg").toString(); // 留言
		//String couponId = paramMap.get("couponId").toString(); // 优惠券id
		// 邮费
		//BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());
		MemberUserDO user = memberUserDao.get(userId);
		int level = user.getLevel(); // 会员等级 0:普通用户1:团长 2:核心 3合伙人
		Date date = new Date();
		// 总支付价格
		BigDecimal payPrice = new BigDecimal(0);
		long payNum = Id.next();
		for (Map<String,Object> cartMap: cartList) {
			int isPostInsurance = MapUtil.getInt(cartMap,"isPostInsurance");
			//优惠券id
			String couponId = cartMap.get("couponId").toString();
			//购物车id
			String cartId = MapUtil.getStr(cartMap,"cartId");
			MemberCartDO cart = memberCartDao.get(cartId);
			String goodId = cart.getGoodsId(); // 商品id
			int total = cart.getNum(); // 商品数量
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodId);

			String productId = cart.getProductId(); // 商品规格id
			GoodsProductDO product = goodsProductDao.get(productId);
			int stock = product.getStock(); // 库存

			//运费
			Map<String,Object> map = new HashMap<>();
			map.put("total",total);
			map.put("addressId",MapUtil.getStr(cartMap,"addressId"));
			BigDecimal postFee = getPostFees(map, goodId, productId,isPostInsurance);
			Integer category = goodsGoodsDO.getCategory();
			// 订单表
			OrderOrderDO order = addOrderInfo(userId,category, postType, payType, user, date, payNum, postFee);

			// 订单配送表
			saveOrderShopping(cartMap, postType, date, order);

			// 订单详情表
			//获取不同身份单价
			BigDecimal price = getOneGoodsPriceLevel(level, product);
			BigDecimal priceC = getOneGoodsPriceLevel(1, product);
			BigDecimal priceZ = getOneGoodsPriceLevel(2, product);
			BigDecimal priceG = getOneGoodsPriceLevel(3, product);

			BigDecimal goodPrice = price.multiply(new BigDecimal(total));// 商品总价
			BigDecimal goodPriceC = priceC.multiply(new BigDecimal(total));// 商品总价
			BigDecimal goodPriceZ = priceZ.multiply(new BigDecimal(total));// 商品总价
			BigDecimal goodPriceG = priceG.multiply(new BigDecimal(total));// 商品总价

			// 保存订单详情
			saveOrderDetail(date, order, goodId, total, product, price, goodPrice);
			// 修改商品库存、销量
			updateStu(productId, total, goodId, stock);
			// 删除购物车
			memberCartDao.remove(cartId);
			//goodPrice = goodPrice.add(goodPrice);
			BigDecimal allPrice = new BigDecimal(0); // 订单总支付金额
			// 优惠券
			allPrice = useCoupon(couponId, postFee, date, order, goodPrice);
			goodPriceC = useCoupon(couponId, postFee, date, order, goodPriceC);
			goodPriceZ = useCoupon(couponId, postFee, date, order, goodPriceZ);
			goodPriceG = useCoupon(couponId, postFee, date, order, goodPriceG);
			//总价加上运险费
			//allPrice=allPrice.add(null==product.getRebateOne()||"".equals(product.getRebateOne())?new BigDecimal("0.00"):product.getRebateOne());

			// order_order补充
			if(isPostInsurance==1){
				order.setPostInsurance(product.getRebateOne());
			}else{
				order.setPostInsurance(new BigDecimal("0.00"));
			}

			order.setPayment(allPrice);
			order.setCouponId(couponId);
			order.setOrdertype(0);
			order.setComent(0);
			order.setPaymentC(goodPriceC);
			order.setPaymentZ(goodPriceZ);
			order.setPaymentG(goodPriceG);
			// 判断支付金额是否大于0
			/*if (allPrice.compareTo(new BigDecimal(0.00)) == 0) {
				order.setStatus(3); // 待发货
			} else {
				order.setStatus(1);
			}*/
			order.setStatus(1);
			orderOrderDao.save(order);
			payPrice=payPrice.add(allPrice);
		}



		/*// 分销用的金额是订单总金额,不算优惠券的
		// 一.开始分销
		if (goodsPrice.compareTo(new BigDecimal(0.00)) == 1) {
			startRebate(user, level, order, goodsPrice);
		}

		// order_order补充

		order.setPayment(allPrice);
		order.setCouponId(couponId);
		order.setOrdertype(0);
		order.setComent(0);
		// 判断支付金额是否大于0
		if (allPrice.compareTo(new BigDecimal(0.00)) == 0) {
			order.setStatus(3); // 待发货
		} else {
			order.setStatus(1);
		}
		// order.setStatus(1);
		orderOrderDao.save(order);*/
		Map<String, Object> mmm = new HashMap<>();
		mmm.put("payNum", payNum);
		mmm.put("payType", 0);
		mmm.put("payment", payPrice);
		mmm.put("status", 1);
		return R.ok().put("data", mmm);

	}

	public OrderOrderDO addOrderInfo(String userId,int category, int postType, int payType, MemberUserDO user, Date date, long payNum, BigDecimal postFee) {
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next()); // 订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setPayNum(payNum+"");
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		if(category==0){
			order.setOrdertype(0);
		}else{
			order.setOrdertype(2);
		}

		//order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);
		order.setPostType(postType);
		order.setPaytype(payType);
		order.setSee(0);
		return order;
	}

	private BigDecimal getOneGoodsPriceLevel(int level, GoodsProductDO product) {
		BigDecimal price = new BigDecimal(0); // 单价
		switch (level) {
		case 0:
			price = product.getPrice();
			break;
		case 1:
			price = product.getPriceC();
			break;
		case 2:
			price = product.getPriceZ();
			break;
		case 3:
			price = product.getPriceG();
			break;
		default:
			price = product.getPrice();
		}
		return price;
	}

	private void saveOrderDetail(Date date, OrderOrderDO order, String goodId, int total, GoodsProductDO goodsProductDO,
			BigDecimal price, BigDecimal goodPrice) {
		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(goodsProductDO.getId());
		detailDO.setPrice(price);
		detailDO.setAllPrice(goodPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		detailDO.setPriceC(goodsProductDO.getPriceC());
		detailDO.setPriceZ(goodsProductDO.getPriceZ());
		detailDO.setPriceG(goodsProductDO.getPriceG());
		orderDetailDao.save(detailDO);
	}

	/*
	 * 订单配送方法
	 */
	private void saveOrderShopping(Map<String, Object> paramMap, int postType, Date date, OrderOrderDO order) {
		//String shopAddress = cmsContentDao.getByType("shop-address").getValue();
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		if (postType == 1) {
			String addressId = paramMap.get("addressId").toString(); // 收货地址
			MemberAddressDO memberAddress = memberAddressDao.get(addressId);
			shipping.setReceiverName(memberAddress.getFullName());
			shipping.setReceiverPhone(memberAddress.getPhone());
			shipping.setReceiverProvince(memberAddress.getProvince());
			shipping.setReceiverCity(memberAddress.getCity());
			shipping.setReceiverCounty(memberAddress.getCounty());
			shipping.setReceiverTown(memberAddress.getTown());
			shipping.setReceiverAddress(memberAddress.getAddress());
		}
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		//shipping.setShopAddress(shopAddress);
		orderShippingDao.save(shipping);
	}

	// 购物车算运费
	public BigDecimal getPostFees(Map<String, Object> paramMap, List<String> cartList) {
		BigDecimal postFee = new BigDecimal("0.00");
		for (String cartId : cartList) {
			MemberCartDO cart = memberCartDao.get(cartId);
			String goodsId = cart.getGoodsId();
			GoodsProductDO goodsProductDO = goodsProductDao.get(cart.getProductId());
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsId);
			if (goodsGoodsDO.getPostSize() == 0) {
				// 通用邮费
				postFee = (postFee.add(goodsProductDO.getPostFee())).multiply(new BigDecimal(cart.getNum()));
			} else if (goodsGoodsDO.getPostSize() == 1) {
				// 模板
				// 收货地址
				MemberAddressDO memberAddress = memberAddressDao.get(paramMap.get("addressId").toString());
				Map<String, Object> shopExpressMoneyMap = new HashMap<>();
				shopExpressMoneyMap.put("name", memberAddress.getProvince());
				shopExpressMoneyMap.put("delFlag", "0");
				List<ShopExpressMoneyDO> shopExpressMoneyList = shopExpressMoneyDao.likeList(shopExpressMoneyMap);
				if (shopExpressMoneyList.size() <= 0) {
					System.out.println("地址信息有误");
					// return
					// R.error("抱歉,"+memberAddress.getProvince()+"地区不到!");
				} else {
					Double weight = goodsProductDO.getWeight();
					// 总重量
					weight = weight * cart.getNum();
					// 向上取整
					Double ceil = Math.ceil(weight);
					int intWeight = ceil.intValue();
					if (intWeight <= shopExpressMoneyList.get(0).getFirstWeight()) {
						postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice());
					} else {
						// 邮费=首重价格+续重价格*续重kg //续重价格 //总重量-首重重量
						postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice())
								.add(shopExpressMoneyList.get(0).getAddPrice().multiply(
										new BigDecimal(intWeight - shopExpressMoneyList.get(0).getFirstWeight())));
					}

				}
			}
		}
		return postFee;
	}

	/**
	 *
	 * @param paramMap  包含total 数量  addressId 地址id
	 * @param goodsId  商品id
	 * @param productId 产品id
	 * @param status 0加运险费 1不加
	 * @return
	 */
	public BigDecimal getPostFees(Map<String, Object> paramMap, String goodsId, String productId,int status) {
		BigDecimal postFee = new BigDecimal("0.00");
		GoodsProductDO goodsProductDO = goodsProductDao.get(productId);
		GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsProductDO.getGoodsId());
		// 数量
		Integer num = Integer.parseInt(paramMap.get("total").toString());
		if (goodsGoodsDO.getPostSize() == 0) {
			// 通用邮费

			//是否合单
			if(goodsGoodsDO.getIsvip()==0){
				//不合单
				postFee = (postFee.add(goodsProductDO.getPostFee())).multiply(new BigDecimal(num));
				//加上运险费
				if(status==1){
					postFee=postFee.add(null==goodsProductDO.getRebateOne()||"".equals(goodsProductDO.getRebateOne())?new BigDecimal("0.00"):goodsProductDO.getRebateOne().multiply(new BigDecimal(num)));
				}

			}else{
				//合单
				postFee = (postFee.add(goodsProductDO.getPostFee()));
				if(status==1) {
					postFee = postFee.add(null == goodsProductDO.getRebateOne() || "".equals(goodsProductDO.getRebateOne()) ? new BigDecimal("0.00") : goodsProductDO.getRebateOne());
				}
			}
			//postFee = (postFee.add(goodsProductDO.getPostFee())).multiply(new BigDecimal(num));
		} else if (goodsGoodsDO.getPostSize() == 1) {
			// 模板
			// 收货地址
			MemberAddressDO memberAddress = memberAddressDao.get(paramMap.get("addressId").toString());
			Map<String, Object> shopExpressMoneyMap = new HashMap<>();
			shopExpressMoneyMap.put("name", memberAddress.getProvince());
			shopExpressMoneyMap.put("delFlag", "0");
			List<ShopExpressMoneyDO> shopExpressMoneyList = shopExpressMoneyDao.likeList(shopExpressMoneyMap);
			if (shopExpressMoneyList.size() <= 0) {
				System.out.println("地址信息有误");
				// return R.error("抱歉,"+memberAddress.getProvince()+"地区不到!");
			}
			if(goodsGoodsDO.getIsvip()==0){
				//不合单
				//重量
				Double weight = goodsProductDO.getWeight();
				//weight = weight * num;
				Double ceil = Math.ceil(weight);
				int intWeight = ceil.intValue();
				if (intWeight <= shopExpressMoneyList.get(0).getFirstWeight()) {
					postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice());

				} else {
					// 邮费=首重价格+续重价格*续重kg //续重价格 //总重量-首重重量
					postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice())
							.add(shopExpressMoneyList.get(0).getAddPrice().multiply(
									new BigDecimal(intWeight - shopExpressMoneyList.get(0).getFirstWeight())));

				}
				postFee=postFee.multiply(new BigDecimal(num));
				if(status==1) {
					postFee = postFee.add(null == goodsProductDO.getRebateOne() || "".equals(goodsProductDO.getRebateOne()) ? new BigDecimal("0.00") : goodsProductDO.getRebateOne().multiply(new BigDecimal(num)));
				}
			}else{
				//合单

				Double weight = goodsProductDO.getWeight();
				weight = weight * num;
				Double ceil = Math.ceil(weight);
				int intWeight = ceil.intValue();
				if (intWeight <= shopExpressMoneyList.get(0).getFirstWeight()) {
					postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice());
				} else {
					// 邮费=首重价格+续重价格*续重kg //续重价格 //总重量-首重重量
					postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice())
							.add(shopExpressMoneyList.get(0).getAddPrice().multiply(
									new BigDecimal(intWeight - shopExpressMoneyList.get(0).getFirstWeight())));
				}
				if(status==1) {
					postFee = postFee.add(null == goodsProductDO.getRebateOne() || "".equals(goodsProductDO.getRebateOne()) ? new BigDecimal("0.00") : goodsProductDO.getRebateOne());
				}
			}

		}
		return postFee;
	}
	private void startRebate(MemberUserDO user, int level, OrderOrderDO order, BigDecimal allPrice
			) {
		if (level == 0||level==-1||level==-2) {
			// 普通用户或者vip
			Map<String, Object> map = new HashMap<>();
			map.put("userId", user.getId());
			map.put("level", "1");
			map.put("upLevel", "1");
			
			//给店长返利
			//1.2查找上级最近一个店长
			map.put("level", "-2");
			CmsContentDO byTypeDz = cmsContentDao.getByType("money_td_dz");
			//返利的金额
			//2.1给店长推荐人返利的金额
			BigDecimal multiplyUp =new BigDecimal("0.00");
			//2.2给店长的团队佣金
			BigDecimal multiply =new BigDecimal("0.00");
			
			List<MemberUserDO> myUpVipDz = memberUserDao.getMyUpVip(map);
			if(myUpVipDz.size()>0){
				multiply = allPrice.multiply(new BigDecimal(byTypeDz.getValue()).multiply(new BigDecimal("0.01")));
				saveOrderCom(order, new BigDecimal("-1"), multiply, myUpVipDz.get(0));
				//查看推荐人
				MemberUserDO memberUserDO = memberUserDao.get(myUpVipDz.get(0).getIntroUser());
				if(memberUserDO!=null&&memberUserDO.getLevel()==-2){
					//如果店长推荐人也是店长,给推荐人返利
					CmsContentDO byTypeUp = cmsContentDao.getByType("money_td_dz_zt");
					multiplyUp = multiply.multiply(new BigDecimal(byTypeUp.getValue()).multiply(new BigDecimal("0.01")));
					saveOrderCom(order, new BigDecimal("-1"), multiplyUp, memberUserDO);
				}
			}
			allPrice=allPrice.subtract(multiply).subtract(multiplyUp);
			
			
			//给vip返商品在收货后,先给上级是vip的话,给代理的返利要减少
			MemberUserDO memberUserDO2 = memberUserDao.get(user.getIntroUser());
			// 1.1查找上级总监
			MemberUserDO memberUserDO = null;
			map.put("level", "1");
			List<MemberUserDO> myUpVip = memberUserDao.getMyUpVip(map);
			if(myUpVip.size()>0){
				memberUserDO=myUpVip.get(0);
			}else{
				//1.2查找上级为总代
				map.put("level", "2");
				List<MemberUserDO> myUpVipA = memberUserDao.getMyUpVip(map);
				if(myUpVipA.size()>0){
					memberUserDO=myUpVipA.get(0);
				}
			}
			if(memberUserDO2!=null&&memberUserDO2.getLevel()==-1&&memberUserDO!=null){
				//如果是第5件,给总监/总代返差价,不返本金
				List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(order.getId());
				
				if(byOrderId.size()>0){
						for (Map<String, Object> map2 : byOrderId) {
							Map<String, Object> stockMap = new HashMap<>();
							stockMap.put("goodsId", map2.get("goodId").toString());
							stockMap.put("userId", memberUserDO2.getId());
							stockMap.put("productId", map2.get("productId").toString());
							stockMap.put("delFlag", "0");
							//还剩的产品规格的数量
							int count = memberStockDao.count(stockMap);
							CmsContentDO byType = cmsContentDao.getByType("num_vip_fl");
							//不够5个的数量
							int c = count % (Integer.parseInt(byType.getValue()));
							int parseInt = Integer.parseInt(map2.get("total").toString());
							c +=parseInt;
							
							//a是只返差价,不返本金的数量
							int a = c / (Integer.parseInt(byType.getValue()));
							//给代理返利,总金额-a件商品金额+a件商品的差价
							
							if(memberUserDO!=null &&memberUserDO.getLevel()==1){
								// //给代理b返利,总金额-a*1件商品的代理价
								GoodsProductDO goodsProductDO = goodsProductDao.get(map2.get("productId").toString());
								allPrice=allPrice.subtract(goodsProductDO.getPriceC().multiply(new BigDecimal(a)));
							}else{
								//1.2查找上级为2的所有人
								if(memberUserDO!=null&&memberUserDO.getLevel()==2){
									////给代理a返利,总金额-a*1件商品的原价
									GoodsProductDO goodsProductDO = goodsProductDao.get(map2.get("productId").toString());
									allPrice=allPrice.subtract(goodsProductDO.getPriceZ().multiply(new BigDecimal(a)));
								}
							}
							//给vip添加库存在下级收货后
						}
				}
			}
			
			//给代理返利
			if(memberUserDO!=null){
				saveOrderCom(order, allPrice, new BigDecimal("0"), memberUserDO);
			}
		} else if (level == 1) {
			Map<String, Object> map = new HashMap<>();
			map.put("level", "1");
			map.put("uplevel", "1");
			map.put("userId", user.getId());
			
			MemberUserDO memberUserDO2 = memberUserDao.get(user.getIntroUser());
			if(memberUserDO2!=null&& memberUserDO2.getLevel()==1){
				//如果上级是总监,给总监返利
				CmsContentDO byType = cmsContentDao.getByType("money-buy-b");
				saveOrderCom(order, new BigDecimal("-1"),allPrice.multiply(new BigDecimal(byType.getValue())) , memberUserDO2);
				//给总代的钱数
				allPrice=allPrice.subtract(allPrice.multiply(new BigDecimal(byType.getValue())));
			}else if(memberUserDO2!=null){
				//给间接总监返利
				
				List<MemberUserDO> myUpVip = memberUserDao.getMyUpVip(map);
				if(myUpVip.size()>0){
					CmsContentDO byType = cmsContentDao.getByType("money_b_b");
					saveOrderCom(order, new BigDecimal("-1"),allPrice.multiply(new BigDecimal(byType.getValue())) , myUpVip.get(0));
					allPrice=allPrice.subtract(allPrice.multiply(new BigDecimal(byType.getValue())));
				}
			}
			//如果有总代,给总代返利
			map.put("level", "2");
			List<MemberUserDO> myUpVip = memberUserDao.getMyUpVip(map);
			if(myUpVip.size()>0){
				saveOrderCom(order, allPrice,new BigDecimal("0") , myUpVip.get(0));
			}
			
			
		} else if (level == 2) {
			//给上级总代返利
			Map<String, Object> map = new HashMap<>();
			map.put("level", "2");
			map.put("uplevel", "1");
			map.put("userId", user.getId());
			
			MemberUserDO memberUserDO2 = memberUserDao.get(user.getIntroUser());
			if(memberUserDO2!=null&& memberUserDO2.getLevel()==2){
				//如果上级是总代,给总代返利
				CmsContentDO byType = cmsContentDao.getByType("money-buy-aa");
				saveOrderCom(order, new BigDecimal("-1"),allPrice.multiply(new BigDecimal(byType.getValue())) , memberUserDO2);
			}else if(memberUserDO2!=null){
				//给间接总代返利
				List<MemberUserDO> myUpVip = memberUserDao.getMyUpVip(map);
				if(myUpVip.size()>0){
					CmsContentDO byType = cmsContentDao.getByType("money_a_a");
					saveOrderCom(order, new BigDecimal("-1"),allPrice.multiply(new BigDecimal(byType.getValue())) , myUpVip.get(0));
				}
			}
		}
	}

	/***
	 * 
	 * @author long 2020年7月7日上午11:47:18 方法释义:返积分,无用 参数:
	 *
	 */
	/*
	 * private void saveMemberScore(MemberUserDO user, OrderOrderDO order,
	 * MemberUserDO upUser, MemberScoreDO memberScoreDO) {
	 * memberScoreDO.setCreateAt(new Date()); memberScoreDO.setDelFlag(0);
	 * memberScoreDO.setGId(order.getId());
	 * memberScoreDO.setId(UUIDUtils.getUUID());
	 * memberScoreDO.setMemberId(user.getId());
	 * if(user.getId().equals(upUser.getId())){ memberScoreDO.setType(3); }else{
	 * memberScoreDO.setType(0); }
	 * 
	 * memberScoreDO.setUserId(upUser.getId());
	 * memberScoreDao.save(memberScoreDO); }
	 */

	/*
	 * allPrice 等于-1 是跟同级返,不等于-1,allprice下级(大)的金额,value上级(小)的金额
	 */
	private void saveOrderCom(OrderOrderDO order, BigDecimal allPrice, BigDecimal value, MemberUserDO up2User) {
		/*
		 * 返的同级推荐人的,直接返
		 */
		if (allPrice.compareTo(new BigDecimal(-1)) == 0) {
			OrderComDO comDO = new OrderComDO();
			comDO.setComPrice(value);
			comDO.setCreateAt(new Date());
			comDO.setDelFlag(1);
			comDO.setOrderId(order.getId());
			comDO.setStatus(0);
			comDO.setUserId(up2User.getId());
			comDO.setId(UUIDUtils.getUUID());
			orderComDao.save(comDO);
		} else {
			// 不是给同级推荐人的
			// 库存修改,返利
			List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(order.getId());
			for (Map<String, Object> map2 : byOrderId) {
				Map<String, Object> map = new HashMap<>();
				map.put("goodsId", map2.get("goodId").toString());
				map.put("productId", map2.get("productId").toString());
				map.put("userId", up2User.getId());
				int count = memberStockDao.findStockNumByUserId(map);
				int total = Integer.parseInt(map2.get("total").toString());
				if (count >= total) {
					// 如果上级库存大于等于订单数量
					OrderComDO comDO = new OrderComDO();
					comDO.setComPrice(allPrice.subtract(value));
					System.out.println("-------------" + comDO.getComPrice());
					comDO.setCreateAt(new Date());
					comDO.setGoodsId(map2.get("goodId").toString());
					comDO.setProductId(map2.get("productId").toString());
					comDO.setDelFlag(1);
					comDO.setOrderId(order.getId());
					comDO.setId(UUIDUtils.getUUID());
					comDO.setNum(total);
					comDO.setStatus(0);
					comDO.setUserId(up2User.getId());
					System.out.println("*******************" + up2User.getId());
					orderComDao.save(comDO);

				} else {
					// 购买的比上级库存多的数
					/*
					 * BigDecimal num = new BigDecimal("0.00"); if(count>0){ num
					 * = new BigDecimal(total - count); }else{ num = new
					 * BigDecimal(total - 0); }
					 * System.out.println("!!!!!!!!!!!!!!!!!!+"+num);
					 */
					BigDecimal price = new BigDecimal(map2.get("price").toString());// 订单详情产品单个金额
					// 上级价格
					// BigDecimal price1 = new BigDecimal("0.00");
					/*
					 * GoodsProductDO goodsProductDO =
					 * goodsProductDao.get(map2.get("productId").toString());
					 */
					/*
					 * BigDecimal priceC = goodsProductDO.getPriceC();
					 * BigDecimal priceZ = goodsProductDO.getPriceZ(); Integer
					 * level = up2User.getLevel();
					 */
					/*
					 * if(level==1){ price1=priceC; }else if(level==2){
					 * price1=priceZ; }else{ System.out.println("返利:用户信息有误"); }
					 */

					BigDecimal subtract = new BigDecimal(0.00);
					BigDecimal subtract1 = new BigDecimal(0.00);
					int num = 0;
					// 可以返的金额 .subtract(price1.multiply(new BigDecimal(count)))
					if (count > 0) {
						subtract = price.multiply(new BigDecimal(count));
						// 库存不够的金额 .subtract(price1.multiply(num))
						subtract1 = price.multiply(new BigDecimal(total - count));
						num = total - count;
					} else {
						subtract = new BigDecimal(0.00);
						// 库存不够的金额 .subtract(price1.multiply(num))
						subtract1 = price.multiply(new BigDecimal(total));
						num = total;
					}

					// 开始返利//可以返的金额
					if (subtract.compareTo(new BigDecimal("0.00")) == 1) {
						OrderComDO comDO = new OrderComDO();
						comDO.setComPrice(subtract);
						comDO.setCreateAt(new Date());
						comDO.setGoodsId(map2.get("goodId").toString());
						comDO.setProductId(map2.get("productId").toString());
						comDO.setDelFlag(1);
						comDO.setNum(count);
						comDO.setOrderId(order.getId());
						comDO.setStatus(0);
						comDO.setId(UUIDUtils.getUUID());
						comDO.setUserId(up2User.getId());
						orderComDao.save(comDO);
					}
					// 开始返利//库存不够的冻结金额
					if (subtract1.compareTo(new BigDecimal("0.00")) == 1) {
						OrderComDO comDO = new OrderComDO();
						comDO.setComPrice(subtract1);
						comDO.setCreateAt(new Date());
						comDO.setGoodsId(map2.get("goodId").toString());
						comDO.setProductId(map2.get("productId").toString());
						comDO.setDelFlag(1);
						comDO.setNum(num);
						comDO.setId(UUIDUtils.getUUID());
						comDO.setOrderId(order.getId());
						comDO.setStatus(1);
						comDO.setUserId(up2User.getId());
						orderComDao.save(comDO);
					}
				}
				// 减去上级库存
				MemberStockDO memberStockDO = new MemberStockDO();
				memberStockDO.setCaAt(new Date());
				memberStockDO.setCause("下级买货");
				memberStockDO.setDelFlag(1);
				memberStockDO.setGoodsId(map2.get("goodId").toString());
				memberStockDO.setId(UUIDUtils.getUUID());
				memberStockDO.setStock(-total);
				memberStockDO.setUserId(up2User.getId());
				memberStockDO.setOrderId(order.getId());
				memberStockDO.setProductId(map2.get("productId").toString());
				memberStockDao.save(memberStockDO);
			}

		}

		/*
		 * if (allPrice.compareTo(new BigDecimal(-1)) == 0) { OrderComDO comDO =
		 * new OrderComDO(); comDO.setComPrice(value); comDO.setCreateAt(new
		 * Date()); comDO.setDelFlag(0); comDO.setOrderId(order.getId());
		 * comDO.setStatus(0); comDO.setUserId(up2User.getId());
		 * orderComDao.save(comDO); } else { OrderComDO comDO = new
		 * OrderComDO(); comDO.setComPrice(allPrice.subtract(value));
		 * comDO.setCreateAt(new Date()); comDO.setDelFlag(0);
		 * comDO.setOrderId(order.getId()); comDO.setStatus(0);
		 * comDO.setUserId(up2User.getId()); orderComDao.save(comDO); }
		 */

	}

	/* 商品详情添加订单，仅限于 普通、秒杀、9.9专区商品、拼团、会员专区 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addGoodsOrder(Map<String, Object> paramMap) {
		Integer type = Integer.valueOf(paramMap.get("type").toString()); // type
																			// 0：普通商品，1:9.9商品，2：秒杀商品，4：拼团商品，5：会员专区商品6:积分商品
		String productId = paramMap.get("productId").toString(); // 规格id
		int postType = Integer.valueOf(paramMap.get("postType").toString()); // 配送方式：0：自提，1：快递
		int isPostInsurance = Integer.valueOf(paramMap.get("isPostInsurance").toString()); // 配送方式：0：自提，1：快递
		int payType = Integer.valueOf(paramMap.get("payType").toString()); // 0：微信支付，1：支付宝支付,
																			// 2积分支付
		String id = paramMap.get("id").toString(); // type为0时传商品id，1:9.9商品,type为 2时传秒杀id，type为
													// type为4时传拼团id，type为5时传会员专区id

		Integer total = Integer.valueOf(paramMap.get("total").toString()); // 商品数量
		String userId = paramMap.get("userId").toString(); // 用户id
		//xString buyerMsg = paramMap.get("buyerMsg").toString(); // 留言
		String couponId = paramMap.get("couponId").toString(); // 优惠券id
		// 邮费
		BigDecimal postFee = new BigDecimal("0.00");
		if(type==2){
			//秒杀商品
			GoodsSpikeDO spikeDO = goodsSpikeDao.get(id);
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(spikeDO.getGoodsId());
			Map<String,Object> map = new HashMap<>();
			map.put("total",total);
			map.put("addressId",MapUtil.getStr(paramMap,"addressId"));
			postFee = getPostFees(map, goodsGoodsDO.getId(), productId,isPostInsurance);
		}else{
			//普通商品
			Map<String,Object> map = new HashMap<>();
			map.put("total",total);
			map.put("addressId",MapUtil.getStr(paramMap,"addressId"));
			postFee = getPostFees(map, id, productId,isPostInsurance);
		}

		//BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());
		MemberUserDO user = memberUserDao.get(userId);
		int level = user.getLevel();
		String goodsId = "";
		Date date = new Date();

		// 订单表
		long payNum = Id.next();
		//添加订单信息
		GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(id);
		OrderOrderDO order = addOrderInfo(userId,goodsGoodsDO.getCategory(), postType, payType, user, date, payNum, postFee);

		// 订单配送表
		saveOrderShopping(paramMap, postType, date, order);

		// 订单详情表

		//支付金额
		//BigDecimal price = new BigDecimal(0);
		BigDecimal goodsPrice = new BigDecimal(0);
		BigDecimal goodsPriceC = new BigDecimal(0);
		BigDecimal goodsPriceZ = new BigDecimal(0);
		BigDecimal goodsPriceG = new BigDecimal(0);
		/*BigDecimal priceC = new BigDecimal(0);
		BigDecimal priceZ = new BigDecimal(0);
		BigDecimal priceG = new BigDecimal(0);*/
		// 判库存，填价格，定返佣，改销量
		GoodsProductDO product = goodsProductDao.get(productId);
		int stock = product.getStock(); // 规格库存
		if (type == 2) { // 秒杀商品
			GoodsSpikeDO spikeDO = goodsSpikeDao.get(id);
			goodsId = spikeDO.getGoodsId();
			goodsPrice = getSpikeMoneyByUser(level, spikeDO);
			goodsPriceC = getSpikeMoneyByUser(1, spikeDO);
			goodsPriceZ = getSpikeMoneyByUser(2, spikeDO);
			goodsPriceG = getSpikeMoneyByUser(3, spikeDO);

			/*goodsPriceC=priceC.multiply(new BigDecimal(total));
			goodsPriceZ=priceZ.multiply(new BigDecimal(total));
			goodsPriceG=priceG.multiply(new BigDecimal(total));
			goodsPrice = price.multiply(new BigDecimal(total));*/
			int spikeNumSale = spikeDO.getNumSale() + total; // 新秒杀销量
			int spikeStoke = spikeDO.getStock(); // 旧库存
			int newSpikeStock = spikeStoke - total; // 新库存
			Map<String, Object> spikeMap = new HashMap<String, Object>();
			if (newSpikeStock < 0) {
				newSpikeStock = 0;
			}
			spikeMap.put("id", id);
			spikeMap.put("newStock", newSpikeStock);
			spikeMap.put("oldStock", spikeStoke);
			spikeMap.put("spikeNumSale", spikeNumSale);
			int n = goodsSpikeDao.updateByOld(spikeMap);
			if (n == 0) {
				goodsProductDao.error(spikeMap);
			}
		} /*else if (type == 4) { // 拼团商品 //无用
			GoodsTeamDO teamDO = goodsTeamDao.get(id);
			goodsId = teamDO.getGoodsId();
			switch (level) {
			case 1:
				price = teamDO.getPriceC();
				break;
			case 2:
				price = teamDO.getPriceZ();
				break;
			case 0:
				price = teamDO.getPrice();
				break;
			default:
				price = teamDO.getPrice();
			}
			goodsPrice = price.multiply(new BigDecimal(total));
			// 总价
			int teamNumSale = teamDO.getNumSale() + total; // 新秒杀销量
			int teamStoke = teamDO.getStock(); // 旧库存
			int newTeamStock = teamStoke - total; // 新库存
			Map<String, Object> teamMap = new HashMap<String, Object>();
			if (newTeamStock < 0) {
				newTeamStock = 0;
			}
			teamMap.put("id", id);
			teamMap.put("newStock", newTeamStock);
			teamMap.put("oldStock", teamStoke);
			teamMap.put("teamNumSale", teamNumSale);
			int n = goodsTeamDao.updateByOld(teamMap);
			if (n == 0) {
				goodsProductDao.error(teamMap);
			}
			order.setDelFlag(1);
			// 添加拼团订单表
			if (!paramMap.containsKey("teamId") || StringUtils.isBlank(paramMap.get("teamId").toString())) {
				OrderTeamDO orderTeamDO = new OrderTeamDO();
				orderTeamDO.setId(UuidUtil.get32UUID());
				orderTeamDO.setGoodsTeamId(id);
				orderTeamDO.setTime(teamDO.getTime());
				orderTeamDO.setNumber(teamDO.getNumber());
				orderTeamDO.setCreateAt(date);
				orderTeamDO.setUpdateAt(DateUtils.addHourOfDate(date, teamDO.getTime()));
				orderTeamDO.setDelFlag(0);
				orderTeamDao.save(orderTeamDO);
				OrderTeamUserDO orderTeamUserDO = new OrderTeamUserDO();
				orderTeamUserDO.setId(UuidUtil.get32UUID());
				orderTeamUserDO.setOrderId(order.getId());
				orderTeamUserDO.setIsMain(1);
				orderTeamUserDO.setCreateAt(date);
				orderTeamUserDO.setUpdateAt(date);
				orderTeamUserDO.setDelFlag(0);
				orderTeamUserDO.setOrderTeamId(orderTeamDO.getId());
				orderTeamUserDao.save(orderTeamUserDO);
			} else {
				OrderTeamUserDO orderTeamUserDO = new OrderTeamUserDO();
				orderTeamUserDO.setId(UuidUtil.get32UUID());
				orderTeamUserDO.setOrderId(order.getId());
				orderTeamUserDO.setIsMain(0);
				orderTeamUserDO.setCreateAt(date);
				orderTeamUserDO.setUpdateAt(date);
				orderTeamUserDO.setDelFlag(0);
				orderTeamUserDO.setOrderTeamId(paramMap.get("teamId").toString());
				orderTeamUserDao.save(orderTeamUserDO);
			}
		} else if (type == 5) { // 会员专区商品 无用
			GoodsUpgradeDO upgradeDO = goodsUpgradeDao.get(id);
			goodsId = upgradeDO.getGoodsId();
			price = upgradeDO.getPrice();
			goodsPrice = price.multiply(new BigDecimal(total));// 总价
			*//*
			 * rebateOnePrice = upgradeDO.getRebateOne().multiply(new
			 * BigDecimal(total)); //一级返佣 rebateTwoPrice =
			 * upgradeDO.getRebateTwo().multiply(new BigDecimal(total)); //二级返佣
			 *//*
			int upgradeNumSale = upgradeDO.getNumSale() + total; // 新秒杀销量
			int upgradeStoke = upgradeDO.getStock(); // 旧库存
			int newUpgradeStock = upgradeStoke - total; // 新库存
			Map<String, Object> upgradeMap = new HashMap<String, Object>();
			if (newUpgradeStock < 0) {
				newUpgradeStock = 0;
			}
			upgradeMap.put("id", id);
			upgradeMap.put("newStock", newUpgradeStock);
			upgradeMap.put("oldStock", upgradeStoke);
			upgradeMap.put("upgradeNumSale", upgradeNumSale);
			int n = goodsUpgradeDao.updateByOld(upgradeMap);
			if (n == 0) {
				goodsProductDao.error(upgradeMap);
			}
		} */else if (type == 0) { // 普通商品
			goodsId = id;

			goodsPrice = getOneGoodsPriceLevel(level, product);
			/*goodsPriceC = getOneGoodsPriceLevel(1, product).multiply(new BigDecimal(total));
			goodsPriceZ = getOneGoodsPriceLevel(2, product).multiply(new BigDecimal(total));
			goodsPriceG = getOneGoodsPriceLevel(3, product).multiply(new BigDecimal(total));*/
			goodsPriceC = getOneGoodsPriceLevel(1, product);
			goodsPriceZ = getOneGoodsPriceLevel(2, product);
			goodsPriceG = getOneGoodsPriceLevel(3, product);
		}

		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodsId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(productId);
		detailDO.setPrice(goodsPrice);
		detailDO.setPriceC(goodsPriceC);
		detailDO.setPriceZ(goodsPriceZ);
		detailDO.setPriceG(goodsPriceG);

		goodsPrice = goodsPrice.multiply(new BigDecimal(total));
		goodsPriceC = goodsPriceC.multiply(new BigDecimal(total));
		goodsPriceZ = goodsPriceZ.multiply(new BigDecimal(total));
		goodsPriceG = goodsPriceG.multiply(new BigDecimal(total));

		detailDO.setAllPrice(goodsPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		if (type == 5) { // 会员专区商品 //无用
			GoodsUpgradeDO upgradeDO = goodsUpgradeDao.get(id);
			detailDO.setUpLevel(upgradeDO.getLevel());
		}
		orderDetailDao.save(detailDO);

		updateStu(productId, total, goodsId, stock);

		// 优惠券
		BigDecimal allPrice = new BigDecimal(0);
		//支付总金额
		allPrice = useCoupon(couponId, postFee, date, order, goodsPrice);
		goodsPriceC = useCoupon(couponId, postFee, date, order, goodsPriceC);
		goodsPriceZ = useCoupon(couponId, postFee, date, order, goodsPriceZ);
		goodsPriceG = useCoupon(couponId, postFee, date, order, goodsPriceG);
		//运险费 加在运费方法里面了
		//allPrice=allPrice.add(null==product.getRebateOne()||"".equals(product.getRebateOne())?new BigDecimal("0.00"):product.getRebateOne());
		// 开始分销,活动商品不参加分销
		/*if (type ==0&&goodsPrice.compareTo(new BigDecimal(0.00)) > 0) {
			System.out.println("开始分销");
			startRebate(user, level, order, goodsPrice);
		}*/

		// order_order补充
		System.out.println("????????" + allPrice);
		if(isPostInsurance==1){
			order.setPostInsurance(product.getRebateOne());
		}else{
			order.setPostInsurance(new BigDecimal("0.00"));
		}

		order.setPayment(allPrice);
		order.setPaymentC(goodsPriceC);
		order.setPaymentZ(goodsPriceZ);
		order.setPaymentG(goodsPriceG);
		order.setCouponId(couponId);
		order.setPaymentG(goodsPriceG);
		order.setPaymentZ(goodsPriceZ);
		order.setPaymentC(goodsPriceC);
		order.setPostInsurance(product.getRebateOne());
		order.setComent(0);
		/*if (allPrice.compareTo(new BigDecimal(0.00)) == 0) {
			order.setStatus(3);// 待发货
		} else {
			order.setStatus(1);
		}*/
		order.setStatus(1);
		System.out.println("]]]]]]]]]]]]]]]]]]" + order.getStatus());
		orderOrderDao.save(order);
		Map<String, Object> mmm = new HashMap<>();
		mmm.put("payNum", payNum+"");
		mmm.put("payType", order.getPaytype());
		mmm.put("status", order.getStatus());
		mmm.put("payment", allPrice);
		return R.ok().put("data", mmm);
	}

	private BigDecimal getSpikeMoneyByUser(int level, GoodsSpikeDO spikeDO) {
		BigDecimal price;
		switch (level) {
		case 0:
			price = spikeDO.getPrice();
			break;
		case 1:
			price = spikeDO.getPriceC();
			break;
		case 2:
			price = spikeDO.getPriceZ();
			break;
		case 3:
			price = spikeDO.getPriceG();
			break;
		default:
			price = spikeDO.getPrice();
		}
		return price;
	}

	/*
	 * 判库存,改销量
	 */
	private void updateStu(String productId, Integer total, String goodsId, int stock) {
		Map<String, Object> proMap = new HashMap<String, Object>();
		/*int newStock = stock - total;
		if (newStock < 0) {
			newStock = 0;
		}*/
		proMap.put("id", productId);
		proMap.put("total", total);
		//proMap.put("oldStock", stock);
		int n = goodsProductDao.updateByOld(proMap);
		/*if (n == 0) {
			goodsProductDao.error(proMap);
		}*/
		int a = goodsProductDao.updateNumSale(proMap);
		proMap.put("goodsId",goodsId);
		// 销量添加
		int goods = goodsGoodsDao.updateNumSale(proMap);
		/*int numSale = 0;
		if (goods != null) {
			numSale = goods.getNumSale();
		}
		int num_sale = numSale + total;
		GoodsGoodsDO good = new GoodsGoodsDO();
		good.setId(goodsId);
		good.setNumSale(num_sale);
		goodsGoodsDao.update(good);*/


	}

	// 使用优惠券方法
	private BigDecimal useCoupon(String couponId, BigDecimal postFee, Date date, OrderOrderDO order,
			BigDecimal goodsPrice) {
		BigDecimal allPrice;
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		// 如果优惠金额比商品金额大,就不用优惠券
		if (memberCouponDO != null && memberCouponDO.getMoney().compareTo(goodsPrice) == -1) {

			BigDecimal couponMoney = memberCouponDO.getMoney(); // 优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney); // 订单总金额
			if(memberCouponDO.getStatus()==0){
				// 修改用户优惠券
				MemberCouponDO couponDO = new MemberCouponDO();
				couponDO.setId(memberCouponDO.getId());
				couponDO.setStatus(1);
				couponDO.setOrderAt(date);
				couponDO.setUpdateAt(date);
				couponDO.setOrderId(order.getId());
				memberCouponDao.update(couponDO);
			}

		} else {
			allPrice = goodsPrice.add(postFee); // 订单总金额
		}
		if(allPrice.compareTo(new BigDecimal("0.00"))==-1){
			allPrice=new BigDecimal("0.01");
		}
		return allPrice;
	}

	/* 购买砍价商品，创建订单--弃用 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addBargainGoodsOrder(Map<String, Object> paramMap) {
		String productId = paramMap.get("productId").toString(); // 规格id
		String bargainId = paramMap.get("bargainId").toString(); // 砍价id
		Integer total = Integer.valueOf(paramMap.get("total").toString()); // 商品数量，固定为
																			// 1
		String userId = paramMap.get("userId").toString(); // 用户id
		String buyerMsg = paramMap.get("buyerMsg").toString(); // 留言
		String couponId = paramMap.get("couponId").toString(); // 优惠券id
		// 邮费
		BigDecimal postFee;
		try {
			GoodsProductDO goodsProductDO = goodsProductDao.get(productId);
			postFee = getPostFees(paramMap, goodsProductDO.getGoodsId(), productId,0);
		} catch (Exception e) {
			return R.error(e.toString());
		}
		// BigDecimal postFee = new
		// BigDecimal(paramMap.get("postFee").toString()); // 邮费
		String addressId = paramMap.get("addressId").toString(); // 收货地址
		MemberUserDO user = memberUserDao.get(userId);
		//int level = user.getLevel();
		Date date = new Date();
		GoodsBargainDO goodsBargainDO = goodsBargainDao.get(bargainId);
		String goodsId = goodsBargainDO.getGoodsId();

		// 订单表
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next()); // 订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);

		// 砍价订单详情
		OrderBargainDO bargainDO = new OrderBargainDO();
		bargainDO.setId(UuidUtil.get32UUID());
		bargainDO.setOrderId(order.getId());
		bargainDO.setDelFlag(0);
		bargainDO.setPrice(goodsBargainDO.getPrice());
		bargainDO.setMinPrice(goodsBargainDO.getMinPrice());
		bargainDO.setMaxPrice(goodsBargainDO.getMaxPrice());
		bargainDO.setRebateOne(goodsBargainDO.getRebateOne());
		bargainDO.setRebateTwo(goodsBargainDO.getRebateTwo());
		bargainDO.setStartAt(date);
		Date endAt = DateUtils.addHourOfDate(date, goodsBargainDO.getTime());
		bargainDO.setEndAt(endAt);
		orderBargainDao.save(bargainDO);

		// 订单配送表
		MemberAddressDO memberAddress = memberAddressDao.get(addressId);
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		shipping.setReceiverName(memberAddress.getFullName());
		shipping.setReceiverPhone(memberAddress.getPhone());
		shipping.setReceiverProvince(memberAddress.getProvince());
		shipping.setReceiverCity(memberAddress.getCity());
		shipping.setReceiverCounty(memberAddress.getCounty());
		shipping.setReceiverTown(memberAddress.getTown());
		shipping.setReceiverAddress(memberAddress.getAddress());
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		orderShippingDao.save(shipping);

		// 订单详情表
		BigDecimal price = new BigDecimal(0);
		BigDecimal goodsPrice = new BigDecimal(0);
		// 判库存，填价格，定返佣，改销量
		GoodsProductDO product = goodsProductDao.get(productId);
		int stock = product.getStock(); // 规格库存
		price = goodsBargainDO.getPrice();
		goodsPrice = price.multiply(new BigDecimal(total));// 总价
		int bargainNumSale = goodsBargainDO.getNumSale() + total; // 新秒杀销量
		int bargainStock = goodsBargainDO.getStock(); // 旧秒杀库存
		int newBarStock = bargainStock - total; // 新秒杀库存
		Map<String, Object> spikeMap = new HashMap<String, Object>();
		if (newBarStock < 0) {
			newBarStock = 0;
		}
		spikeMap.put("id", bargainId);
		spikeMap.put("newStock", newBarStock);
		spikeMap.put("oldStock", bargainStock);
		spikeMap.put("numSale", bargainNumSale);
		int n = goodsBargainDao.updateByOld(spikeMap);
		if (n == 0) {
			goodsProductDao.error(spikeMap);
		}

		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodsId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(productId);
		detailDO.setPrice(price);
		detailDO.setAllPrice(goodsPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		orderDetailDao.save(detailDO);
		updateStu(productId, total, goodsId, stock);

		BigDecimal allPrice = new BigDecimal(0);
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		if (memberCouponDO != null) {
			BigDecimal couponMoney = memberCouponDO.getMoney(); // 优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney); // 订单总金额
			// 修改用户优惠券
			MemberCouponDO couponDO = new MemberCouponDO();
			couponDO.setId(memberCouponDO.getId());
			couponDO.setStatus(1);
			couponDO.setOrderAt(date);
			couponDO.setUpdateAt(date);
			couponDO.setOrderId(order.getId());
			memberCouponDao.update(couponDO);
		} else {
			allPrice = goodsPrice.add(postFee); // 订单总金额
		}

		// 开始分销
		// startRebate(user, level, order, allPrice);
		/*
		 * String intorId = user.getIntroUser(); for (int i=1; i<3; i++) { if
		 * (intorId == null || "".equals(intorId)) { break; } MemberUserDO
		 * productUser = memberUserDao.get(intorId); if (productUser == null) {
		 * break; } int disbled = productUser.getDisabled(); if (disbled == 1) {
		 * //如果账号被冻结,找下一个 i--; intorId = productUser.getIntroUser(); continue; }
		 * 
		 * BigDecimal money = new BigDecimal(0); if (i == 1) { money =
		 * rebateOnePrice; } else if (i == 2) { money = rebateTwoPrice; }
		 * OrderComDO comDO = new OrderComDO();
		 * comDO.setId(UuidUtil.get32UUID()); comDO.setCreateAt(date);
		 * comDO.setDelFlag(0); comDO.setOrderId(order.getId());
		 * comDO.setComPrice(money); comDO.setStatus(0);
		 * comDO.setUpdateAt(date); comDO.setUserId(intorId);
		 * orderComDao.save(comDO); intorId = productUser.getIntroUser(); }
		 */
		// order_order补充
		order.setPayment(allPrice);
		order.setCouponId(couponId);
		order.setOrdertype(3);
		order.setStatus(0);
		order.setComent(0);
		orderOrderDao.save(order);
		return R.ok();
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public PageInfo<Map<String, Object>> getOrderListByStatus(Map<String, Object> paramMap) {
		// 更新拼团订单状态
		List<Map<String, Object>> updateList = orderOrderDao.getTeamOrderStatus(paramMap);
		for (Map<String, Object> updateMap : updateList) {
			int paytype = Integer.valueOf(updateMap.get("paytype").toString());
			String orderId = updateMap.get("orderId").toString();
			if (paytype == 2) { // 余额支付
				// 复原余额
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("gId", orderId);
				map.put("type", "0");
				MemberPriceDO memberPriceDO = memberPriceDao.list(map).get(0);
				memberPriceDO.setDelFlag(1);
				memberPriceDao.update(memberPriceDO);
			} else if (paytype == 0) { // 微信支付
				R r = weChatPayService.refund(updateMap);
			}
			OrderOrderDO orderOrderDO = new OrderOrderDO();
			orderOrderDO.setId(updateMap.get("orderId").toString());
			orderOrderDO.setStatus(10);
			orderOrderDao.update(orderOrderDO);
		}

		PageHelperUtils.page(paramMap);
		String type = paramMap.get("type").toString(); // 类型
		String userId = paramMap.get("userId").toString(); // 会员id
		String[] status = new String[10];
		if (type.equals("1")) { // 待支付
			status[0] = "1";
		} else if (type.equals("2")) { // 待发货
			status[0] = "3";
		} else if (type.equals("7")) { // 拼团中
			status[0] = "2";
		} else if (type.equals("3")) { // 待收货
			status[0] = "4";
		} else if (type.equals("4")) { // 待评价
			status[0] = "7";
		} else if (type.equals("5")) { // 问题订单
			status[0] = "5"; //退货中
			status[1] = "6"; //退货成功
			status[2] = "11"; //换货中
		} else if (type.equals("0")) { // 全部
			// status[0] = "0";
			status[0] = "1";
			status[1] = "2";
			status[2] = "3";
			status[3] = "4";
			status[4] = "7";
			status[6] = "8";
			status[7] = "10";
			/*
			 * status[9] = "9"; status[10] = "10";
			 */
		}
		paramMap.put("status", status);
		List<Map<String, Object>> list = orderOrderDao.getOrderListByStatus(paramMap);
		for (Map<String, Object> map : list) {
			String orderId = map.get("id").toString();
			List<Map<String, Object>> detailList = orderDetailDao.getByOrderId(orderId);
			for (Map<String, Object> stringObjectMap : detailList) {
				if(StrUtil.isBlank(MapUtil.getStr(map,"priceY"))){
					stringObjectMap.put("priceY",MapUtil.getStr(stringObjectMap,"price"));
				}
			}
			map.put("detailList", detailList);
			if(StrUtil.isBlank(MapUtil.getStr(map,"paymentY"))){
				map.put("paymentY",MapUtil.getStr(map,"payment"));
			}
		}
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	/* 会员取消订单、收货 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int setStatusOrder(Map<String, Object> paramMap) {
		String userId = paramMap.get("userId").toString();
		String orderId = paramMap.get("orderId").toString();
		String type = paramMap.get("type").toString();
		Date date = new Date();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("id", orderId);
		OrderOrderDO orderDO = orderOrderDao.get(orderId);
		MemberUserDO userDO = memberUserDao.get(userId);
		List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(orderId);
		GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(byOrderId.get(0).get("goodId").toString());
		int total = MapUtil.getInt(byOrderId.get(0),"total");
		if ("8".equals(type)) { // 取消订单
			if (orderDO.getStatus() != 1) {
				return 1;
			}
			//OrderOrderDO order = new OrderOrderDO();
			//order.setId(orderId);
			orderDO.setStatus(8);
			orderDO.setUpdateAt(date);
			if(paramMap.containsKey("msg")&&null !=paramMap.get("msg")){
				orderDO.setBuyerMsg(MapUtil.getStr(paramMap,"msg"));
			}
			orderOrderDao.update(orderDO);
			// 删除返利的佣金
			orderComDao.removeCom(orderId);
			//返还优惠券
			if(StringUtils.isNoneBlank(orderDO.getCouponId())){
				MemberCouponDO memberCouponDO = memberCouponDao.get(orderDO.getCouponId());
				if(memberCouponDO!=null){
					SalesCouponDO salesCouponDO = salesCouponDao.get(memberCouponDO.getCouponId());
					if(salesCouponDO.getLimitEndat().after(new Date())){
						memberCouponDO.setStatus(2);
					}else{
						memberCouponDO.setStatus(0);
					}
					memberCouponDao.update(memberCouponDO);
				}
			}




			cancelMesage(orderDO, userDO, goodsGoodsDO, total,0);
			//同步视频号订单取消
			//syncShopOrderPay(orderDO,userDO,3,"");


			//往平台公告表加入数据
			CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
			cmsNoticeDO.setId(IdUtil.simpleUUID());
			cmsNoticeDO.setContent("您订单号为:"+orderDO.getOrderSn()+"的订单已取消成功,包含商品"+goodsGoodsDO.getName()+"!取消时间:"+DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN)+",如需帮助,请联系客服!");
			cmsNoticeDO.setDelFlag(0);
			cmsNoticeDO.setCaAt(new Date());
			cmsNoticeDO.setTitle("订单取消通知");
			cmsNoticeDO.setUserId(orderDO.getUserId());
			cmsNoticeDao.save(cmsNoticeDO);



			// 删除减掉的库存
			//int a = memberStockDao.removeStock(orderId);
			//System.out.println(a);
			/*
			 * // 删除返的(扣除)积分 memberScoreDao.removeScore(orderId);
			 */
		} else if ("7".equals(type)) { // 收货
			if (orderDO.getStatus() != 4 ) {
				return 1;
			}
			OrderOrderDO order = new OrderOrderDO();
			order.setId(orderId);
			order.setStatus(7);
			order.setUpdateAt(date);
			order.setReceivingAt(date);
			order.setEndAt(date);
			orderOrderDao.update(order);
			// 修改佣金到账
			updateCmsAndScore(date, order);

			//同步视频号订单收货
			//syncRecieveOrder(orderDO);
			//发送订阅消息
			//cancelMesage(orderDO, userDO, goodsGoodsDO, total,0);
			ShopExpressCodeDO shopExpressCodeDO = shopExpressCodeDao.queryByCode(orderDO.getShippingName());
			receivingMessage(orderDO, userDO, goodsGoodsDO, total, order, shopExpressCodeDO,0);




			//往平台公告表加入数据
			CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
			cmsNoticeDO.setId(IdUtil.simpleUUID());
			cmsNoticeDO.setContent("您订单号为:"+orderDO.getOrderSn()+"的订单已收货成功!收货时间:"+DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN)+",如需帮助,请联系客服!");
			cmsNoticeDO.setDelFlag(0);
			cmsNoticeDO.setCaAt(new Date());
			cmsNoticeDO.setTitle("订单收货通知");
			cmsNoticeDO.setUserId(order.getUserId());
			cmsNoticeDao.save(cmsNoticeDO);
			
			
		}
		return 0;
	}

	private void receivingMessage(OrderOrderDO orderDO, MemberUserDO userDO, GoodsGoodsDO goodsGoodsDO, int total, OrderOrderDO order, ShopExpressCodeDO shopExpressCodeDO,int flag) {
		//订单收货通知
		try {
			//支付成功提醒
			//发送订阅消息
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();

			subscribeMessage.setToUser(userDO.getWechatOpenId());
			subscribeMessage.setTemplateId(Constants.mesage.MODE_ORDER_CANCEL);
			subscribeMessage.setPage(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+ order.getId());

			List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
			for (int i = 0; i < 5; i++) {
				WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
				switch (i) {
					case 0:
						data.setName("character_string1");
						data.setValue(order.getOrderSn());
						break;
					case 1:
						data.setName("thing7");
						data.setValue(goodsGoodsDO.getName()+"*"+ total);
						break;
					case 2:

						data.setName("phrase2");
						if(flag==0){
							data.setValue("已签收");
						}else{
							data.setValue("自动签收");
						}

						break;
					case 3:
						data.setName("name3");
						data.setValue(shopExpressCodeDO.getName());
						break;
					case 4:
						data.setName("character_string4");

						data.setValue(orderDO.getShippingCode());
						break;
					default:
						break;
				}
				list.add(data);


			}
			subscribeMessage.setData(list);
			wxService.getMsgService().sendSubscribeMsg(subscribeMessage); //发送订阅消息
		} catch (WxErrorException e) {
			e.printStackTrace();

		}
	}

	private void cancelMesage(OrderOrderDO orderDO, MemberUserDO userDO, GoodsGoodsDO goodsGoodsDO, int total,int flag) {
		//订单取消通知
		try {
			//支付成功提醒
			//发送订阅消息
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();

			subscribeMessage.setToUser(userDO.getWechatOpenId());
			subscribeMessage.setTemplateId(Constants.mesage.MODE_ORDER_CANCEL);
			subscribeMessage.setPage(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+ orderDO.getId());

			List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
			for (int i = 0; i < 5; i++) {
				WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
				switch (i) {
					case 0:
						data.setName("character_string1");
						data.setValue(orderDO.getOrderSn());
						break;
					case 1:
						data.setName("thing4");
						data.setValue(goodsGoodsDO.getName()+"*"+ total);
						break;
					case 2:
						data.setName("amount3");
						data.setValue(orderDO.getPayment()+"");
						break;
					case 3:
						data.setName("date2");
						data.setValue(DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN));
						break;
					case 4:
						data.setName("thing8");
						if(flag==0){
							if(orderDO.getBuyerMsg().length()>20){
								data.setValue(orderDO.getBuyerMsg().substring(0,19));
							}else{
								data.setValue(orderDO.getBuyerMsg());
							}

						}else{
							data.setValue("超时自动取消");
						}

						break;
					default:
						break;
				}
				list.add(data);


			}
			subscribeMessage.setData(list);
			wxService.getMsgService().sendSubscribeMsg(subscribeMessage); //发送订阅消息
		} catch (WxErrorException e) {
			e.printStackTrace();

		}
	}

	private void syncRecieveOrder(OrderOrderDO orderDO){
		try {
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaShopOrderService wxMaShopOrderService = new WxMaShopOrderServiceImpl(wxService);

			MemberUserDO memberUserDO = memberUserDao.get(orderDO.getUserId());
			WxMaShopOrderRecieveRequest wxMaShopOrderRecieveRequest = new WxMaShopOrderRecieveRequest();
			wxMaShopOrderRecieveRequest.setOutOrderId(orderDO.getId());
			wxMaShopOrderRecieveRequest.setOpenid(memberUserDO.getWechatOpenId());
			WxMaShopBaseResponse wxMaShopBaseResponse = wxMaShopOrderService.orderRecieve(wxMaShopOrderRecieveRequest);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}

	private void updateUserLevel(String userId, String orderId, MemberUserDO userDO) {
		if (userDO.getLevel() < 1) {
			// 查看已完成的订单金额
			BigDecimal allMoney = orderOrderDao.countOrderMoneyByUserId(userId);
			System.out.println("zzzzzzzzzzzzzzzzzzz:" + allMoney);
			System.out.println("lllllllllllllllllll:" + userDO.getLevel());
			if (userDO.getLevel() == 0) {
				/*// 普通用户晋升总代
				CmsContentDO byTypeA = cmsContentDao.getByType("num-up-b");
				BigDecimal moneyA = new BigDecimal(byTypeA.getValue());
				if (allMoney.compareTo(moneyA) >= 0) {
					// 添加等级变动记录
					changeLevel(userDO, 0, 2, "用户直接晋级总代");
					// 添加库存
					// 把所有商品规格,都添加到库存列表里,用户可以进货
					putStock(userId);
				}else {
					// 普通用户升级总监
					CmsContentDO byType = cmsContentDao.getByType("num-up-b");
					BigDecimal money = new BigDecimal(byType.getValue());
					if (allMoney.compareTo(money) >= 0) {
						// 添加等级变动记录
						changeLevel(userDO, 0, 1, "用户直接晋级总监");
						// 添加库存
						// 把所有商品规格,都添加到库存列表里,用户可以进货
						putStock(userId);
					}else{
						// 普通用户升级vip
						CmsContentDO byTypeVip = cmsContentDao.getByType("money-up-vip");
						BigDecimal moneyVip = new BigDecimal(byTypeVip.getValue());
						if (allMoney.compareTo(moneyVip) >= 0) {
							// 添加等级变动记录
							changeLevel(userDO, 0, -1, "用户晋级vip");
						}
						// 查看上级vip有没有达到升级条件
						// 1.0 获取上级vip
						List<MemberUserDO> memberUserDOList = memberUserDao.getMyUpVip(userId);
						if (memberUserDOList.size() > 0) {
							for (MemberUserDO memberUserDO : memberUserDOList) {
								//查看所有上级vip有没有达到升级条件
								upVip(memberUserDO.getId());
							}
						}
					}
				}*/
				// 普通用户升级店长
				CmsContentDO byTypeDz = cmsContentDao.getByType("money_user_dz");
				BigDecimal moneyDz = new BigDecimal(byTypeDz.getValue());
				if (allMoney.compareTo(moneyDz) >= 0) {
					// 添加等级变动记录
					changeLevel(userDO, 0, -2, "用户晋级店长");
					//putStock(userDO.getId());
				}else{
					// 普通用户升级vip
					CmsContentDO byTypeVip = cmsContentDao.getByType("money-up-vip");
					BigDecimal moneyVip = new BigDecimal(byTypeVip.getValue());
					if (allMoney.compareTo(moneyVip) >= 0) {
						// 添加等级变动记录
						changeLevel(userDO, 0, -1, "用户晋级vip");
						putStock(userDO.getId());
					}
				}
				
				
				// 查看上级vip有没有达到升级条件
				// 1.0 获取上级vip
				Map<String, Object> map = new HashMap<>();
				map.put("level", -1);
				map.put("userId", userId);
				List<MemberUserDO> memberUserDOList = memberUserDao.getMyUpVip(map);
				if (memberUserDOList.size() > 0) {
					for (MemberUserDO memberUserDO : memberUserDOList) {
						//查看所有上级vip有没有达到升级条件
						upVip(memberUserDO.getId());
					}
				}
				
				
			} else if (userDO.getLevel() == -1) {
				// 1-vip直接升级店长
				CmsContentDO byType = cmsContentDao.getByType("money-up-dz");
				BigDecimal money = new BigDecimal(byType.getValue());
				OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
				if (orderOrderDO.getPayment().compareTo(money) >= 0) {
					// 用户升级为店长
					changeLevel(userDO, -1, -2, "vip一次性购买产品晋升店长");
				} else {
					// vip间接升级店长
					upVip(userId);
				}
			} else if (userDO.getLevel() == 1) {
				// 1.总监直接升总代
				CmsContentDO byTypeUp = cmsContentDao.getByType("money_up_a");
				if (allMoney.compareTo(new BigDecimal(byTypeUp.getValue())) >= 0) {
					// 1.1添加等级变动记录
					changeLevel(userDO, 1, 2, "总监直接升总代");
				}
				// 2.总监累计升级总代
				CmsContentDO byType = cmsContentDao.getByType("num-up-a");
				System.out.println("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww" + byType.getValue());
				// 2.1获取总监自己的消费金额
				BigDecimal countOrderMoneyByUserId = orderOrderDao.countOrderMoneyByUserId(userId);
				if (countOrderMoneyByUserId.compareTo(new BigDecimal(byType.getValue())) >= 0) {
					// 2.2添加等级变动记录
					changeLevel(userDO, 1, 2, "总监累计升总代");

				}
			}
		}

	}

	private void putStock(String userId) {
		List<Map<String, Object>> list = goodsProductDao.getByNotInStock(userId);
		if (list.size() > 0) {
			for (Map<String, Object> stockMap : list) {
					MemberStockDO memberStockDO = new MemberStockDO();
					memberStockDO.setCaAt(new Date());
					memberStockDO.setCause("晋级添加所有商品到库存列表");
					memberStockDO.setDelFlag(0);
					memberStockDO.setGoodsId(stockMap.get("goodsId").toString());
					memberStockDO.setId(UUIDUtils.getUUID());
					memberStockDO.setProductId(stockMap.get("productId").toString());
					memberStockDO.setStock(0);
					memberStockDO.setUserId(userId);
					memberStockDao.save(memberStockDO);
			}
		}
	}
	
	//上级用户id
	private void upVip(String userId) {
		// 没有一次性购买,查看团队成绩
		// 1.直推vip个数
		Map<String, Object> map = new HashMap<>();
		map.put("level", "-1");
		map.put("introUser", userId);
		map.put("delFlag", "0");
		int myFansHCount = memberUserDao.count(map);
		// 升级所需人数
		CmsContentDO cmsContentDO = cmsContentDao.getByType("num-up-dz-vip");
		if (myFansHCount >= Integer.parseInt(cmsContentDO.getValue())) {
			// 2.团队等级大于等于vip个数
			map.put("userId", userId);
			map.put("gtType", "0");
			map.put("ltType", "0");
			int count = memberUserDao.getMyFansCountGtVip(map);
			// 2.1升级所需金额
			CmsContentDO cmsContentDO1 = cmsContentDao.getByType("num-up-dz-td");
			if (count >= Integer.parseInt(cmsContentDO1.getValue())) {
				// 3.查看团队消费金额
				BigDecimal tmMoney = orderOrderDao.getMyFansCountMoney(userId);
				// 3.1升级所需团队消费金额
				CmsContentDO cmsContentDOMoney = cmsContentDao.getByType("money-up-dz-td");
				if (tmMoney.compareTo(new BigDecimal(cmsContentDOMoney.getValue())) >= 0) {
					// 4.升级
					// 升级为店长
					MemberUserDO memberUserDO = memberUserDao.get(userId);
					changeLevel(memberUserDO, -1, -2, "vip间接升级店长");
				}
			}
		}

		// 3.团队消费额
	}

	private void changeLevel(MemberUserDO userDO, int oldLevel, int newLevel, String coment) {
		MemberLevelChangeDO changeDO = new MemberLevelChangeDO();
		changeDO.setId(UuidUtil.get32UUID());
		changeDO.setOldLevel(oldLevel);
		changeDO.setNewLevel(newLevel);
		changeDO.setCreateAt(new Date());
		changeDO.setUpdateAt(new Date());
		changeDO.setDelFlag(0);
		changeDO.setUserId(userDO.getId());
		changeDO.setComent(coment);
		memberLevelChangeDao.save(changeDO);
		userDO.setLevel(newLevel);
		memberUserDao.update(userDO);
	}

	/* 后台自提成功,弃用 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R ziTi(OrderOrderDO order) {
		/*
		 * String orderId = order.getId(); Date date = new Date();
		 * order.setStatus(7); order.setUpdateAt(date);
		 * order.setReceivingAt(date); order.setEndAt(date);
		 * orderOrderDao.update(order); //插入我的余额表 Map<String,Object> map = new
		 * HashMap<String,Object>(); map.put("orderId", orderId);
		 * List<OrderComDO> comDOList = orderComDao.list(map); for (OrderComDO
		 * orderComDO : comDOList) { MemberPriceDO priceDO = new
		 * MemberPriceDO(); priceDO.setId(UuidUtil.get32UUID());
		 * priceDO.setGId(orderId); priceDO.setType(3); priceDO.setDelFlag(0);
		 * priceDO.setCreateAt(date); priceDO.setUpdateAt(date);
		 * priceDO.setUserId(orderComDO.getUserId());
		 * priceDO.setPrice(orderComDO.getComPrice());
		 * memberPriceDao.save(priceDO); } //插入积分记录 OrderOrderDO orderOrderDO =
		 * orderOrderDao.get(orderId); BigDecimal value = new
		 * BigDecimal(cmsContentDao.getByType("score-buy").get(0).getValue());
		 * BigDecimal score =
		 * value.multiply(orderOrderDO.getPayment()).divide(new
		 * BigDecimal(100)); MemberScoreDO scoreDO = new MemberScoreDO();
		 * scoreDO.setId(UuidUtil.get32UUID()); scoreDO.setType(0);
		 * scoreDO.setUserId(orderOrderDO.getUserId()); scoreDO.setDelFlag(0);
		 * scoreDO.setCreateAt(date); scoreDO.setUpdateAt(date);
		 * scoreDO.setGId(order.getId()); scoreDO.setMoney(score);
		 * memberScoreDao.save(scoreDO);
		 */
		return R.ok();
	}

	/* 去评论 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int setComent(Map<String, Object> paramMap) {
		String userId = paramMap.get("userId").toString();
		String orderId = paramMap.get("orderId").toString();
		Date date = new Date();
		List<Map<String, Object>> comentList = (List<Map<String, Object>>) (paramMap.get("comentList"));
		for (Map<String, Object> comentMap : comentList) {
			if (comentMap.get("start") == null || "".equals(comentMap.get("start").toString())) {
				return 2;
			}
			int start = new Integer(comentMap.get("start").toString());
			String content = comentMap.get("content").toString();
			String detailId = comentMap.get("detailId").toString();
			String imgurls = StringUtils.getString(comentMap.get("imgurls"));
			if (StringUtils.isBlank(content)) {
				return 1;
			}
			// 评论表
			OrderComentDO comentDO = new OrderComentDO();
			comentDO.setId(UuidUtil.get32UUID());
			comentDO.setContent(content);
			comentDO.setDetailId(detailId);
			comentDO.setStar(start);
			comentDO.setDisply(0);
			comentDO.setCreateAt(date);
			comentDO.setUserId(userId);
			comentDO.setImgurls(imgurls);
			orderComentDao.save(comentDO);
			// 修改detail表
			OrderDetailDO detailDO = new OrderDetailDO();
			detailDO.setId(detailId);
			detailDO.setComent(1);
			orderDetailDao.update(detailDO);
			// 修改商品评论量
			OrderDetailDO orderDetailDO = orderDetailDao.get(detailId);
			String goodsId = orderDetailDO.getGoodsId();
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsId);
			int newNum = goodsGoodsDO.getNumComment() + 1;
			GoodsGoodsDO goodsDO = new GoodsGoodsDO();
			goodsDO.setId(goodsId);
			goodsDO.setNumComment(newNum);
			goodsGoodsDao.update(goodsDO);
		}
		OrderOrderDO orderOrderDO = new OrderOrderDO();
		orderOrderDO.setId(orderId);
		orderOrderDO.setComent(1);
		orderOrderDao.update(orderOrderDO);
		return 0;
	}

	@Override
	public Map<String, Object> getOrderById(Map<String, Object> paramMap) {
		Map<String, Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		int allTotal = 0;
		for (OrderDetailDO detailDO : detailList) {
			Map<String, Object> map = new HashMap<String, Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			allTotal = allTotal + detailDO.getTotal();
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);

			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName", goodsDO.getName());
			map.put("goodsPrice", goodsPrice);

			if(productDO!=null){
				map.put("spec", productDO.getSpec());
			}else{
				map.put("spec", goodsDO.getSpec());
			}
			map.put("goodsId", goodsDO.getId());
			map.put("detailId", detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("goodsList", goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		orderMap.put("allTotal", allTotal);
		// 查询优惠券金额

		String coupon_id = StringUtils.getString(orderMap.get("coupon_id"));
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice", couponDO.getMoney());
		}
		String orderId = paramMap.get("orderId").toString();
		OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
		if (orderOrderDO.getStatus() == 6 || orderOrderDO.getStatus() == 5) {
			OrderBackDO orderBackDO = orderBackDao.getByOrderId(orderId);
			orderMap.put("orderBackDO", orderBackDO);
		}

		if(StringUtils.isNotBlank(orderOrderDO.getShippingName())){
			ShopExpressCodeDO shopExpressCodeDO = shopExpressCodeDao.queryByCode(orderOrderDO.getShippingName());

			if(shopExpressCodeDO!=null){
				orderMap.put("expreesName",shopExpressCodeDO.getName());
			}else{
				orderMap.put("expreesName","");
			}
		}else{
			orderMap.put("expreesName","");
		}

		return orderMap;
	}

	/* 拼团订单详情 */
	@Override
	public Map<String, Object> getPOrderById(Map<String, Object> paramMap) {
		Map<String, Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		int allTotal = 0;
		for (OrderDetailDO detailDO : detailList) {
			Map<String, Object> map = new HashMap<String, Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			allTotal = allTotal + detailDO.getTotal();
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName", goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", productDO.getSpec());
			map.put("goodsId", goodsDO.getId());
			map.put("detailId", detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("goodsList", goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		orderMap.put("allTotal", allTotal);
		// 得到拼团信息
		Map<String, Object> teamMap = orderTeamUserDao.getTeamByOrderId(paramMap);
		orderMap.put("needNUm", teamMap.get("number"));
		orderMap.put("endTeamTime", teamMap.get("update_at"));
		// 查询优惠券金额
		String coupon_id = StringUtils.getString(orderMap.get("coupon_id"));
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice", couponDO.getMoney());
		}
		// 查询拼团人
		List<Map<String, Object>> userList = orderTeamUserDao.getUserByOrder(paramMap);
		orderMap.put("userList", userList);
		return orderMap;
	}

	/* 砍价订单详情 */
	@Override
	public Map<String, Object> getKOrderById(Map<String, Object> paramMap) {
		Map<String, Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		for (OrderDetailDO detailDO : detailList) {
			Map<String, Object> map = new HashMap<String, Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName", goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", "");
			map.put("goodsId", goodsDO.getId());
			map.put("detailId", detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("goodsList", goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		// 查询优惠券金额
		String coupon_id = StringUtils.getString(orderMap.get("coupon_id"));
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice", couponDO.getMoney());
		}
		// 查询帮忙砍价人
		List<Map<String, Object>> userList = orderBargainUserDao.getUserByOrder(paramMap);
		orderMap.put("userList", userList);
		return orderMap;
	}

	@Override
	public List<Map<String, Object>> getOrderList(Map<String, Object> map) {
		return orderOrderDao.getOrderList(map);
	}

	@Override
	public int getOrderListCount(Map<String, Object> map) {
		return orderOrderDao.getOrderListCount(map);
	}

	/**
	 * 添加物流
	 * 
	 * @param order
	 * @return
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int addShipping(OrderOrderDO order) {
		OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
		Date date = new Date();
		ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
		ShopExpressMessageDO messageDO = shopExpressMessageDao.queryByOrderId(order.getId());


		List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(order.getId());
		GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(MapUtil.getStr(byOrderId.get(0), "goodId"));
		MemberUserDO memberUserDO = memberUserDao.get(orderOrderDO.getUserId());
		if (messageDO == null && codeDO != null) {
			order.setStatus(4);
			order.setUpdateAt(date);
			order.setConsignAt(date);
			orderOrderDao.update(order);

			messageDO = new ShopExpressMessageDO();
			messageDO.setId(UuidUtil.get32UUID());
			messageDO.setStatus(0);
			messageDO.setName(codeDO.getName());
			// messageDO.setCode(order.getShippingCode());
			messageDO.setCode(codeDO.getCode());
			messageDO.setExpressId(order.getShippingCode());
			messageDO.setUserId(order.getUserId());
			messageDO.setDelFlag(Constant.DEFAULT_DEL_FLAG);
			messageDO.setOpAt(new Date());
			messageDO.setOrderId(order.getId());
			shopExpressMessageDao.save(messageDO);

			//同步视频号订单发货
			try {
				final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
				//WxMaShopDeliveryService wxMaShopDeliveryService = new WxMaShopDeliveryServiceImpl(wxService);
				//WxMaShopGetCompanyListResponse companyList = wxMaShopDeliveryService.getCompanyList();
				WxMaShopOrderService wxMaShopOrderService = new WxMaShopOrderServiceImpl(wxService);
				WxMaShopOrderSendRequest wxMaShopOrderSendRequest = new WxMaShopOrderSendRequest();
				wxMaShopOrderSendRequest.setOutOrderId(orderOrderDO.getId());
				wxMaShopOrderSendRequest.setOpenid(memberUserDO.getWechatOpenId());
				WxMaShopDeliveryItem wxMaShopDeliveryItem = new WxMaShopDeliveryItem();
				wxMaShopDeliveryItem.setDeliveryId(codeDO.getCode()); //快递简称
				wxMaShopDeliveryItem.setWaybillId(order.getShippingCode());//物流号
				List<WxMaShopDeliveryItem> list = new ArrayList<>();
				wxMaShopOrderSendRequest.setDeliveryList(list);
				wxMaShopOrderSendRequest.setFinishAllDelivery("1");
				WxMaShopBaseResponse wxMaShopBaseResponse = wxMaShopOrderService.orderSend(wxMaShopOrderSendRequest);
				System.out.println(wxMaShopBaseResponse.toString());
			} catch (WxErrorException e) {
				e.printStackTrace();
			}

			// 推送
			/*
			 * OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
			 * String userId = orderOrderDO.getUserId(); List<String> newList =
			 * new ArrayList<String>(); newList.add(userId); String content =
			 * "您的订单已发货，订单号为："+orderOrderDO.getOrderSn();
			 * jPushService.checkPush(newList, content, 0, "0");
			 */
			// 发信息
			/*
			 * Map<String,Object> shippingMap
			 * =orderOrderDao.getOrderById(order.getId()); String mobile =
			 * shippingMap.get("receiver_phone").toString(); String name =
			 * shippingMap.get("name").toString(); String shippingCode =
			 * orderOrderDO.getShippingCode(); String code = " "+name+
			 * "已发货，详情请查询 "+codeDO.getName()+"："+shippingCode+""; try {
			 * JuSms.sendFSms(mobile, code); } catch (IOException e) {
			 * e.printStackTrace(); return 1; }
			 *
			 *
			 */

			try {

				//发送订阅消息
				final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
				WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
				subscribeMessage.setToUser(memberUserDO.getWechatOpenId());
				subscribeMessage.setTemplateId(Constants.mesage.MODE_ORDER_DELIVER);
				subscribeMessage.setPage(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+order.getId());
				List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
				for (int i = 0; i < 5; i++) {
					WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
					switch (i) {
						case 0:
							data.setName("character_string7");
							data.setValue(orderOrderDO.getOrderSn());
							break;
						case 1:
							data.setName("thing5");
							data.setValue(goodsGoodsDO.getName());
							break;
						case 2:
							data.setName("character_string3");
							data.setValue(order.getShippingName());
							break;
						case 3:
							data.setName("thing14");
							data.setValue(codeDO.getName());
							break;
						case 4:
							data.setName("date6");
							data.setValue(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
							break;
						default:
							break;
					}
					list.add(data);


				}
				subscribeMessage.setData(list);
				wxService.getMsgService().sendSubscribeMsg(subscribeMessage); //发送订阅消息
			} catch (WxErrorException e) {
				e.printStackTrace();

			}
				//往平台公告表加入数据
				CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
				cmsNoticeDO.setId(IdUtil.simpleUUID());
				cmsNoticeDO.setContent("您购买的"+goodsGoodsDO.getName()+"*"+MapUtil.getStr(byOrderId.get(0), "total")+"的订单已发货!订单号为"+order.getOrderSn()+",物流名:"+order.getShippingName()+",物流单号:"+order.getShippingCode()+".祝你购物愉快!");
				cmsNoticeDO.setDelFlag(0);
				cmsNoticeDO.setCaAt(new Date());
				cmsNoticeDO.setTitle("发货通知");
				cmsNoticeDO.setUserId(orderOrderDO.getUserId());
				cmsNoticeDao.save(cmsNoticeDO);

			return 1;
		}
		return 0;
	}

	/**
	 * 修改物流
	 * 
	 * @param order
	 * @return
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int editShipping(OrderOrderDO order) {
		Date date = new Date();
		String orderId = order.getId();
		ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
		ShopExpressMessageDO messageDO = shopExpressMessageDao.queryByOrderId(orderId);
		if (messageDO != null && codeDO != null) {
			order.setStatus(4);
			order.setUpdateAt(date);
			order.setConsignAt(date);
			orderOrderDao.update(order);

			// 先删除旧信息
			shopExpressMessageDao.remove(messageDO.getId());
			shopExpressDetailsDao.removeByOrderId(orderId);

			ShopExpressMessageDO newMessageDO = new ShopExpressMessageDO();
			newMessageDO.setId(UuidUtil.get32UUID());
			newMessageDO.setStatus(0);
			newMessageDO.setName(codeDO.getName());
			// newMessageDO.setCode(order.getShippingCode());
			newMessageDO.setCode(codeDO.getCode());
			newMessageDO.setExpressId(order.getShippingCode());
			newMessageDO.setUserId(order.getUserId());
			newMessageDO.setDelFlag(Constant.DEFAULT_DEL_FLAG);
			newMessageDO.setOpAt(new Date());
			newMessageDO.setOrderId(order.getId());
			shopExpressMessageDao.save(newMessageDO);

			OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
			MemberUserDO memberUserDO = memberUserDao.get(orderOrderDO.getUserId());
			List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(orderOrderDO.getId());
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(MapUtil.getStr(byOrderId.get(0),"goodId"));

			try {

				//发送订阅消息
				final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
				WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
				subscribeMessage.setToUser(memberUserDO.getWechatOpenId());
				subscribeMessage.setTemplateId(Constants.mesage.MODE_ORDER_DELIVER);
				subscribeMessage.setPage(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+order.getId());
				List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
				for (int i = 0; i < 5; i++) {
					WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
					switch (i) {
						case 0:
							data.setName("character_string7");
							data.setValue(orderOrderDO.getOrderSn());
							break;
						case 1:
							data.setName("thing5");
							data.setValue(goodsGoodsDO.getName());
							break;
						case 2:
							data.setName("character_string3");
							data.setValue(order.getShippingName());
							break;
						case 3:
							data.setName("thing14");
							data.setValue(codeDO.getName());
							break;
						case 4:
							data.setName("date6");
							data.setValue(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
							break;
						default:
							break;
					}
					list.add(data);


				}
				subscribeMessage.setData(list);
				wxService.getMsgService().sendSubscribeMsg(subscribeMessage); //发送订阅消息
			} catch (WxErrorException e) {
				e.printStackTrace();

			}
			//往平台公告表加入数据
			CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
			cmsNoticeDO.setId(IdUtil.simpleUUID());
			cmsNoticeDO.setContent("您购买的"+goodsGoodsDO.getName()+"*"+MapUtil.getStr(byOrderId.get(0), "total")+"的订单,修改地址成功!订单号为"+order.getOrderSn()+",物流名:"+order.getShippingName()+",物流单号:"+order.getShippingCode()+".祝你购物愉快!");
			cmsNoticeDO.setDelFlag(0);
			cmsNoticeDO.setCaAt(new Date());
			cmsNoticeDO.setTitle("发货通知");
			cmsNoticeDO.setUserId(orderOrderDO.getUserId());
			cmsNoticeDao.save(cmsNoticeDO);


			// 推送
			/*
			 * OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
			 * String userId = orderOrderDO.getUserId(); List<String> newList =
			 * new ArrayList<String>(); newList.add(userId); String content =
			 * "您的订单已发货，订单号为："+orderOrderDO.getOrderSn();
			 * jPushService.checkPush(newList, content, 0, "0");
			 */
			return 1;
		}
		return 0;
	}

	@Override
	public Map<String, Object> getHOrderById(String id) {
		return orderOrderDao.getHOrderById(id);
	}

	@Override
	public List<Map<String, Object>> statisticsList(Map<String, Object> map) {
		return orderOrderDao.statisticsList(map);
	}

	@Override
	public int statisticsCount(Map<String, Object> map) {
		return orderOrderDao.statisticsCount(map);
	}

	@Override
	public List<Map<String, Object>> getDetailGoods(Map<String, Object> map) {
		return orderOrderDao.getDetailGoods(map);
	}

	@Override
	public int getDetailGoodsCount(Map<String, Object> map) {
		return orderOrderDao.getDetailGoodsCount(map);
	}

	@Override
	public List<Map<String, Object>> getKUsers(Map<String, Object> map) {
		return orderOrderDao.getKUsers(map);
	}

	@Override
	public int getKUsersCount(Map<String, Object> map) {
		return orderOrderDao.getKUsersCount(map);
	}

	/* 导出excel。改变订单导出状态 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void exportExcel(Map<String, Object> map, List<Map<String, Object>> userList, ServletOutputStream out,
			HttpServletRequest request) {
		// 导出excel
		if (OrderExcelUtils.exportUserExcel(userList, out) == 1) {
			// 改变订单导出状态
			int number = orderOrderDao.updateExportByMap(map);
			// 添加导出记录
			Long customId = getUserId();
			String userName = userDao.get(customId).getUsername(); // 管理员账号
			OrderExcelRecodeDO recode = new OrderExcelRecodeDO();
			recode.setId(UuidUtil.get32UUID());
			recode.setCreateAt(new Date());
			recode.setUserPhone(userName);
			recode.setNumber(number);
			recode.setIp(IPUtils.getIp(request));
			orderExcelRecodeDao.save(recode);
		}
	}

	/*
	 * 导入excel表格
	 */
	@Override
	public void importExcel(MultipartFile file, String excelFileName) {
		// 1.创建输入流
		try {
			// FileInputStream inputStream = new FileInputStream(file);
			// boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			// 1.读取工作簿
			boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			Workbook workbook = is03Excel ? new HSSFWorkbook(file.getInputStream())
					: new XSSFWorkbook(file.getInputStream());
			// Workbook workbook = new HSSFWorkbook(file.getInputStream());
			// 2.读取工作表
			Sheet sheet = workbook.getSheetAt(0);
			// 3.读取行
			// 判断行数大于一,是因为数据从第二行开始插入
			int num = sheet.getPhysicalNumberOfRows();
			if (sheet.getPhysicalNumberOfRows() > 1) {
				// 跳过前一行
				for (int k = 1; k < sheet.getPhysicalNumberOfRows(); k++) {
					// 读取单元格
					Row row0 = sheet.getRow(k);
					// 订单id
					Cell cell0 = row0.getCell(0);
					cell0.setCellType(Cell.CELL_TYPE_STRING);
					String order_sn = cell0.getStringCellValue().replace("\t", "").trim();
					// 物流名
					String shipping_name = "";
					Cell cell9 = row0.getCell(1);
					if (cell9 == null) {
						shipping_name = "";
					} else {
						cell9.setCellType(Cell.CELL_TYPE_STRING);
						shipping_name = cell9.getStringCellValue().replace("\t", "").trim();
					}
					// 物流单号
					String shipping_code = "";
					Cell cell10 = row0.getCell(2);
					if (cell10 == null) {
						shipping_code = "";
					} else {
						cell10.setCellType(Cell.CELL_TYPE_STRING);
						shipping_code = cell10.getStringCellValue().replace("\t", "").trim();
					}
					if (!("".equals(order_sn.trim()) || "".equals(shipping_name.trim())
							|| "".equals(shipping_code.trim()))) {
						OrderOrderDO ceOrder = orderOrderDao.getByOrder(order_sn);
						int status = ceOrder.getStatus();
						String id = ceOrder.getId();
						if (status == 6) {
							OrderOrderDO order = new OrderOrderDO();
							order.setId(id);
							order.setShippingName(shipping_name.trim());
							order.setShippingCode(shipping_code.trim());
							order.setUserId(ceOrder.getUserId());
							addShipping(order);
						}
					}
				}
			}
			workbook.close();
			// inputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* 后台退货列表 */
	@Override
	public List<Map<String, Object>> getBackOrderList(Map<String, Object> map) {
		return orderOrderDao.getBackOrderList(map);
	}

	@Override
	public int getBackOrderListCount(Map<String, Object> map) {
		return orderOrderDao.getBackOrderListCount(map);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int backOrder(OrderOrderDO order) {
//		System.out.println(1/0);
		String orderId = order.getId();
		int status = order.getStatus();
		order.setUpdateAt(new Date());
		OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
		if (5 != orderOrderDO.getStatus()) {
			return 0;
		}
		MemberUserDO memberUserDO = memberUserDao.get(orderOrderDO.getUserId());
		if (status == 1) { // 同意退货
			OrderBackDO byOrderId = orderBackDao.getByOrderId(orderId);
			byOrderId.setStatus(1);
			byOrderId.setUpdateAt(new Date());
			orderBackDao.update(byOrderId);
			// 清除返利
			//删除返利和业绩
			orderComDao.updateByOrderId(orderId);
//			orderComService.removeCom(orderId);
			OrderTeamMoneyDO orderTeamMoneyDO = new OrderTeamMoneyDO();
			orderTeamMoneyDO.setOrderId(orderId);
			orderTeamMoneyDO.setDelFlag(1);
			orderTeamMoneyDO.setUpAt(new Date());
			orderTeamMoneyService.update(orderTeamMoneyDO);
			// 复原上级库存
			//memberStockDao.updateByOrderId(orderId);
			// 销量和库存恢复原状
			Map<String, Object> mm = new HashMap<>();
			mm.put("orderId", orderId);
			List<OrderDetailDO> detailList = orderDetailDao.list(mm);
			for (OrderDetailDO detail : detailList) {
				String goodsId = detail.getGoodsId();
				String productId = detail.getProductId();
				int total = detail.getTotal();
				// 库存添加
				GoodsProductDO pr = goodsProductDao.get(productId);
				if(pr!=null){
					//GoodsProductDO pro = new GoodsProductDO();
					//int newStock = pr.getStock() + total;
					pr.setStock(pr.getStock() + total);
					//pro.setId(productId);
					//.setStock(newStock);
					goodsProductDao.update(pr);
				}

				// 销量减去
				GoodsGoodsDO goods = goodsGoodsDao.get(goodsId);
				if(goods!=null){
					int num_sale = goods.getNumSale() - total;
					GoodsGoodsDO good = new GoodsGoodsDO();
					good.setId(goodsId);
					good.setNumSale(num_sale);
					goodsGoodsDao.update(good);
				}

			}
			//改变视频号售后状态
			//updateLiveAfterSale(orderId, memberUserDO,6,0);

		} else if (status == 4) { // 驳回
			/*int postType = orderOrderDO.getPostType();
			if (postType == 0) {
				order.setStatus(11);
			} else if (postType == 1) {
				order.setStatus(4);
			}*/

			order.setStatus(4);

			orderOrderDao.update(order);
			orderBackDao.removeByOrder(orderId);
			//改变视频号售后状态
			//updateLiveAfterSale(orderId, memberUserDO,5,1);
		}else if(status == 6){
			//退款完成
			OrderBackDO byOrderId = orderBackDao.getByOrderId(orderId);
			byOrderId.setStatus(4);
			byOrderId.setUpdateAt(new Date());
			orderBackDao.update(byOrderId);
			orderOrderDao.update(order);
			//改变视频号售后状态
			//updateLiveAfterSale(orderId, memberUserDO,14,1);
		}

		returnMessage(order, orderOrderDO,memberUserDO,status);
		return 1;
	}

	/* status 0:未受理,1:用户取消,2:商家受理中,3:商家逾期未处理,4:商家拒绝退款,5:商家拒绝退货退款,
	6:待买家退货,7:退货退款关闭,8:待商家收货,11:商家退款中,12:商家逾期未退款,13:退款完成,
	14:退货退款完成,15:换货完成,16:待商家发货,17:待用户确认收货,18:商家拒绝换货,19:商家已收到货

	finishAllAftersale 0:售后未结束, 1:售后结束且订单状态流转
	*/
	private void updateLiveAfterSale(String orderId, MemberUserDO memberUserDO,int status,int finishAllAftersale){
		try {
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaShopAfterSaleService wxMaShopAfterSaleService = new WxMaShopAfterSaleServiceImpl(wxService);
			WxMaShopAddAfterSaleRequest wxMaShopAddAfterSaleRequest = new WxMaShopAddAfterSaleRequest();
			wxMaShopAddAfterSaleRequest.setOutOrderId(orderId);
			wxMaShopAddAfterSaleRequest.setFinishAllAftersale(finishAllAftersale);
			wxMaShopAddAfterSaleRequest.setOpenid(memberUserDO.getWechatOpenId());
			wxMaShopAddAfterSaleRequest.setStatus(status);
			wxMaShopAfterSaleService.updateAfterSale(wxMaShopAddAfterSaleRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void returnMessage(OrderOrderDO order, OrderOrderDO orderOrderDO,MemberUserDO memberUserDO,int status) {
		try {

			//发送订阅消息
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
			subscribeMessage.setToUser(memberUserDO.getWechatOpenId());
			subscribeMessage.setTemplateId(Constants.mesage.MODE_ORDER_REFUND);
			subscribeMessage.setPage(Constants.mesage.address.ADDRESS_ORDER_INFO+"?id="+ order.getId());
			List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
			for (int i = 0; i < 5; i++) {
				WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
				switch (i) {
					case 0:
						data.setName("thing1");
						if(status==6){
							data.setValue("审核通过,退款成功");
						}else{
							data.setValue("审核失败,联系客服");
						}

						break;
					case 1:
						data.setName("character_string2");
						data.setValue(orderOrderDO.getOrderSn());
						break;
					case 2:
						data.setName("phrase9");
						if(status==6){
							data.setValue("审核通过");
						}else{
							data.setValue("驳回");
						}
						break;
					case 3:
						data.setName("amount3");
						data.setValue(orderOrderDO.getPayment()+"");
						break;
					case 4:
						data.setName("date4");
						data.setValue(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
						break;
					default:
						break;
				}
				list.add(data);


			}
			subscribeMessage.setData(list);
			wxService.getMsgService().sendSubscribeMsg(subscribeMessage); //发送订阅消息
		} catch (Exception e) {
			e.printStackTrace();

			//往平台公告表加入数据
			CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
			cmsNoticeDO.setId(IdUtil.simpleUUID());
			String s = "";
			if(status==6){
				s = "通过";
			}else{
				s = "驳回";
			}
			cmsNoticeDO.setContent("您申请的退货订单,"+"订单号为"+ order.getOrderSn()+"审核状态:"+s);
			cmsNoticeDO.setDelFlag(0);
			cmsNoticeDO.setCaAt(new Date());
			cmsNoticeDO.setTitle("退货通知");
			cmsNoticeDO.setUserId(orderOrderDO.getUserId());
			cmsNoticeDao.save(cmsNoticeDO);

		}

	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int backGood(Map<String, Object> paramMap) {
		Date date = new Date();
		String id = paramMap.get("id").toString();
		String expressName = StringUtils.getString(paramMap.get("expressName"));
		String expressCode = StringUtils.getString(paramMap.get("expressCode"));
		String reason = paramMap.get("reason").toString();

		// 修改订单表
		OrderOrderDO order = new OrderOrderDO();
		order.setId(id);
		order.setStatus(5);
		order.setReturnAt(date);
		order.setUpdateAt(date);
		orderOrderDao.update(order);
		// 添加退货记录
		OrderBackDO orderBackDO = new OrderBackDO();
		orderBackDO.setId(UuidUtil.get32UUID());
		orderBackDO.setOrderId(id);
		orderBackDO.setExpressName(expressName);
		orderBackDO.setExpressCode(expressCode);
		orderBackDO.setReason(reason);
		orderBackDO.setStatus(0);
		orderBackDO.setPhone(MapUtil.getStr(paramMap,"phone"));
		orderBackDO.setCreateAt(date);
		if(paramMap.containsKey("reasonAdd")){
			orderBackDO.setReasonAdd(MapUtil.getStr(paramMap,"reasonAdd"));
		}
		if(paramMap.containsKey("img")){
			orderBackDO.setImg(MapUtil.getStr(paramMap,"img"));
		}

		orderBackDO.setUpdateAt(date);
		orderBackDO.setDelFlag(0);
		orderBackDao.save(orderBackDO);

		addLiveAfterSale(id, orderBackDO);

		// 推送
		 /* List<String> sList = new ArrayList<String>(); OrderOrderDO
		  orderOrderDO = orderOrderDao.get(id); Object oneId =
		  orderOrderDO.getUserH(); Object twoId = orderOrderDO.getUserL(); if
		  (oneId != null && !("".equals(oneId))) { sList.add(oneId.toString());
		  if (twoId != null && !("".equals(twoId))) {
		  sList.add(twoId.toString()); } String content =
		  "您提交的订单已经申请退货，订单号为："+orderOrderDO.getOrderSn();
		  jPushService.checkPush(sList, content, 0, "0"); }*/
		return 1;
	}

	private void addLiveAfterSale(String id, OrderBackDO orderBackDO) {
		try {
			OrderOrderDO orderOrderDO = orderOrderDao.get(id);
			//同步视频添加售后
			MemberUserDO memberUserDO = memberUserDao.get(orderOrderDO.getUserId());
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaShopAfterSaleService wxMaShopAfterSaleService = new WxMaShopAfterSaleServiceImpl(wxService);
			WxMaShopAddAfterSaleRequest wxMaShopAddAfterSaleRequest = new WxMaShopAddAfterSaleRequest();
			wxMaShopAddAfterSaleRequest.setOutOrderId(orderOrderDO.getId());
			wxMaShopAddAfterSaleRequest.setStatus(2);
			wxMaShopAddAfterSaleRequest.setOpenid(memberUserDO.getWechatOpenId());
			wxMaShopAddAfterSaleRequest.setCreateTime(DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN));
			wxMaShopAddAfterSaleRequest.setFinishAllAftersale(0);
			wxMaShopAddAfterSaleRequest.setOutAftersaleId(orderBackDO.getId());
			wxMaShopAddAfterSaleRequest.setPath(Constants.mesage.address.ADDRESS_ORDER_INFO);
			wxMaShopAddAfterSaleRequest.setType(2);
			//商品信息
			WxMaShopAfterSaleProductInfo wxMaShopAfterSaleProductInfo = new WxMaShopAfterSaleProductInfo();
			List<Map<String, Object>> orderDetailList = orderDetailDao.getByOrderId(orderOrderDO.getId());
			GoodsProductDO goodsProductDO = goodsProductDao.get(MapUtil.getStr(orderDetailList.get(0), "productId"));
			wxMaShopAfterSaleProductInfo.setOutProductId(MapUtil.getStr(orderDetailList.get(0),"goodId"));
			wxMaShopAfterSaleProductInfo.setProductCnt(MapUtil.getInt(orderDetailList.get(0), "total"));
			wxMaShopAfterSaleProductInfo.setOutSkuId(goodsProductDO.getId());
			List<WxMaShopAfterSaleProductInfo> productInfos = new ArrayList<>();
			productInfos.add(wxMaShopAfterSaleProductInfo);
			wxMaShopAddAfterSaleRequest.setProductInfos(productInfos);
			HashMap<Object, Object> objectObjectHashMap = MapUtil.newHashMap();
			objectObjectHashMap.put("out_order_id",orderOrderDO.getId());
			objectObjectHashMap.put("openid",memberUserDO.getWechatOpenId());
			/*String s = JSONUtil.toJsonStr(objectObjectHashMap);
			String accessToken = wxService.getAccessToken();
			String post = HttpUtil.post("https://api.weixin.qq.com/shop/order/get?access_token="+accessToken, s);
			System.out.println(post);*/
			wxMaShopAfterSaleService.addAfterSale(wxMaShopAddAfterSaleRequest);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}

	@Override
	public OrderOrderDO getByOrder(String orderSn) {
		return orderOrderDao.getByOrder(orderSn);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R removeOrder(Map<String, Object> map) {
		String userId = map.get("userId").toString();
		List<String> orderIdList = (List<String>) (map.get("orderIdList"));
		MemberUserDO user = memberUserDao.get(userId);
		if (user == null) {
			return R.error("会员信息错误");
		}
		for (String orderId : orderIdList) {
			OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
			int status = orderOrderDO.getStatus();
			if (status == 7 || status == 6 || status == 8 || status == 9 || status == 10) {
				OrderOrderDO order = new OrderOrderDO();
				order.setId(orderId);
				order.setSee(1);
				orderOrderDao.update(order);
			}
		}
		return R.ok();
	}

	/* 支付修改订单状态 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R pricePay(Map<String, Object> params) {
		String orderId = params.get("orderId").toString();
		String userId = params.get("userId").toString();
		System.out.println("userId+"+userId);
		System.out.println("orderid:"+orderId);
		OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
		int orderType = orderOrderDO.getOrdertype()==null?0:orderOrderDO.getOrdertype(); // 订单类型
		//商品id
		List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(orderId);
		System.out.println("byOrderId+"+byOrderId.toString());
		String goodsId = MapUtil.getStr(byOrderId.get(0),"goodId");

		//GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsId);
		String productId = MapUtil.getStr(byOrderId.get(0),"productId");
		GoodsProductDO goodsProductDO = goodsProductDao.get(productId);
		Integer num = MapUtil.getInt(byOrderId.get(0),"total");
		//用户
		MemberUserDO memberUserDO = memberUserDao.get(userId);
		int level = memberUserDO.getLevel();
		if (orderType == 4) { // 拼团订单
			orderOrderDO.setStatus(2);
			orderOrderDO.setDelFlag(0);
		} else {
			System.out.println("开始返利");
			//先给自己算业绩
			saveOrderTeamOrder(orderId, orderOrderDO, memberUserDO);
			//开始返利
			//1.获取用户的无限上级
			List<MemberUserDO> infiniteUpUserList = memberUserDao.getInfiniteUpUser(userId);
			System.out.println("infiniteUpUserList.size()"+infiniteUpUserList.size());
			if(infiniteUpUserList.size()>0){
				int flag=0;//标志,证明是第几个等级
				int dqlevel =level; //当前等级
				//BigDecimal dangQianChajia = new BigDecimal("0.00");//当前差价
				//MemberUserDO daUser = new MemberUserDO(); //当前吃差价的用户
				//for (MemberUserDO upUser : infiniteUpUserList) {
				for (int i = 0; i < infiniteUpUserList.size(); i++) {
					/*if(i==infiniteUpUserList.size()){
						//是最后一次循环

						//如果当前用户是空,或者当前差价是0.00,证明没有吃差价得用户,不用保存差价
						if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
							break;
						}
						//保存当前差价(就是上一次差价减去给上级返利得钱)
						saveOrderCom(orderId, dangQianChajia, goodsId, productId, num, daUser,"-1");

						break;

					}else{
						//保存当前差价(就是上一次差价减去给上级返利得钱)
						saveOrderCom(orderId, dangQianChajia, goodsId, productId, num, daUser,"-1");
					}*/
					MemberUserDO upUser = infiniteUpUserList.get(i);
					if(dqlevel< upUser.getLevel()){




						//当前等级小于 上级等级 吃差价
						//当前等级价格
						BigDecimal dqMoney;
						switch (dqlevel) {
							case 0:
								dqMoney = orderOrderDO.getPayment();
								break;
							case 1:
								dqMoney = orderOrderDO.getPaymentC();
								break;
							case 2:
								dqMoney = orderOrderDO.getPaymentZ();
								break;
							case 3:
								dqMoney = orderOrderDO.getPaymentG();
								break;
							default:
								dqMoney = orderOrderDO.getPayment();
						}

						//获取已经给出的接单价(返利)金额
						Map<String,Object> outMoneyMap = new HashMap<>();
						outMoneyMap.put("orderId",orderId);
						outMoneyMap.put("comUser",upUser.getId());
						outMoneyMap.put("delFlag","0");
						BigDecimal outMoney = orderComDao.sumComUserMoney(outMoneyMap);
						//差价金额
						BigDecimal price =  new BigDecimal("0.00");
						switch (upUser.getLevel()) {
							case 1:
								price = dqMoney.subtract(orderOrderDO.getPaymentC()).subtract(outMoney);
								break;
							case 2:
								price = dqMoney.subtract(orderOrderDO.getPaymentZ()).subtract(outMoney);
								break;
							case 3:
								price = dqMoney.subtract(orderOrderDO.getPaymentG()).subtract(outMoney);
								break;

						}
						//dangQianChajia=price;

						//保存团队业绩信息
						saveOrderTeamOrder(orderId, orderOrderDO, upUser);
						//保存差价
						saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");


						//吃完差价,当前等级等于吃差价的用户等级
						dqlevel=upUser.getLevel();
						//当前用户等于吃差价得用户
						//daUser = upUser;
						//吃完差价,把flag 赋值为0
						flag=0;

						continue;

					}else if(dqlevel>0){
						//上级等级要大于0 才是代理,才有返利

						//返利金额
						BigDecimal rebateTwo = goodsProductDO.getRebateTwo();

						//如果是吃完差价的第一次进来,根据等级返利
						if(flag==0&&dqlevel==1&&upUser.getLevel()==1){
							//如果当前等级是1 上级是团长吃返佣 团长吃团长团长差一级返利

							/*//获取出接单价(出返利)的人,也就是上级吃返利的人,
							Map<String,Object> vipMap = new HashMap<>();
							vipMap.put("level",dqlevel);
							vipMap.put("userId",upUser.getId());
							List<MemberUserDO> myUpVip = memberUserDao.getMyUpVip(vipMap);*/


							String value = cmsContentDao.getByType("money-tz-tz").getValue();
							BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
							//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
							/*//保存返利
							if(myUpVip.size()>0){
								saveOrderCom(orderId, price, goodsId, productId, num, upUser,myUpVip.get(0).getId());
							}else{
								saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
							}*/
							findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
							/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
								saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
							}else{
								saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
							}*/

							//保存团队业绩信息
							saveOrderTeamOrder(orderId, orderOrderDO, upUser);
							flag++;
							continue;
						}else if(flag < 2 &&dqlevel==2){



							//如果当前等级是核心
							if(flag ==0 && upUser.getLevel()==1){
								//如果当前等级是核心,上级是团长吃核心团长差一级返利

								String value = cmsContentDao.getByType("money-hx-tz-one").getValue();

								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利

								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息
								saveOrderTeamOrder(orderId, orderOrderDO, upUser);
								flag++;
								continue;
							}else if(flag ==0&& upUser.getLevel()==2){
								//如果当前等级是核心,上级是核心吃核心核心差一级返利

								String value = cmsContentDao.getByType("money-hx--hx-one").getValue();
								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息
								saveOrderTeamOrder(orderId, orderOrderDO, upUser);
								flag++;
								continue;
							}else if (flag ==1&& upUser.getLevel()==2){
								//如果当前等级是核心,上二级是核心吃核心核心差两级返利

								String value = cmsContentDao.getByType("money-hx-hx-two").getValue();
								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息
								saveOrderTeamOrder(orderId, orderOrderDO, upUser);


								flag++;
								continue;
							}

							flag++;
							continue;
						}else if(flag<3 && dqlevel == 3 ){
							if(flag ==0 && upUser.getLevel()==1){
								//如果当前等级是合伙人,上级是团长吃合伙人团长返利
								String value = cmsContentDao.getByType("money_hhr-tz-one").getValue();
								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息
								saveOrderTeamOrder(orderId, orderOrderDO, upUser);

								flag++;
								continue;
							}else if(flag ==0&& upUser.getLevel()==2){
								//如果当前等级是合伙人,上级是核心吃合伙人核心差一级返利
								String value = cmsContentDao.getByType("money_hhr-hx-one").getValue();

								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息
								saveOrderTeamOrder(orderId, orderOrderDO, upUser);
								flag++;
								continue;
							}else if (flag ==1&& upUser.getLevel()==2){
								//如果当前等级是合伙人,上二级是核心吃合伙人核心差两级返利
								String value = cmsContentDao.getByType("money_hhr-hx-two").getValue();
								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息
								saveOrderTeamOrder(orderId, orderOrderDO, upUser);

								flag++;
								continue;
							}else if(flag ==0&& upUser.getLevel()==3){
								//如果当前等级是合伙人,上级是合伙人吃合伙人合伙人差一级返利
								String value = cmsContentDao.getByType("money_hhr-hhr-one").getValue();

								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = new BigDecimal(value).multiply(new BigDecimal(100)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//保存返利
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息,合伙人是个体,不算业绩
								//saveOrderTeamOrder(orderId, orderOrderDO, upUser);

								flag++;
								continue;
							}else if(flag ==1&& upUser.getLevel()==3){
								//如果当前等级是合伙人,上两级级是合伙人吃合伙人合伙人差两级返利
								String value = cmsContentDao.getByType("money_hhr-hhr-two").getValue();
								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息,合伙人是个体,不算业绩
								//saveOrderTeamOrder(orderId, orderOrderDO, upUser);

								flag++;
								continue;
							}else if(flag ==2&& upUser.getLevel()==3){
								//如果当前等级是合伙人,上三级级是合伙人吃合伙人合伙人差三级返利

								String value = cmsContentDao.getByType("money_hhr-hhr-three").getValue();
								BigDecimal price = rebateTwo.multiply(new BigDecimal(value)).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_EVEN);
								//BigDecimal price = rebateTwo.divide(new BigDecimal(value).multiply(new BigDecimal("100")), 2, BigDecimal.ROUND_HALF_UP);
								//保存返利
								/*if(null==daUser||dangQianChajia.compareTo(new BigDecimal("0.00"))==0){
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,"-1");
								}else{
									saveOrderCom(orderId, price, goodsId, productId, num, upUser,daUser.getId());
								}*/
								findUpUserAndSaveOrderCom(orderId, goodsId, productId, num, dqlevel, upUser, price);
								//saveOrderCom(orderId, price, goodsId, productId, num, upUser);
								//保存团队业绩信息,合伙人是个体,不算业绩
								//saveOrderTeamOrder(orderId, orderOrderDO, upUser);
								flag++;
								//如果返了3级,就不用再后面找了,返利结束,进行最后一次循环
								i=infiniteUpUserList.size();
								continue;
							}

							flag++;
							continue;
						}
					}

				}
			}
		}
		System.out.println("返利完成+");
		orderOrderDO.setStatus(3);
		orderOrderDO.setPayAt(new Date());
		orderOrderDao.update(orderOrderDO);

		//同步视频号订单
		//syncShopOrderPay(orderOrderDO, memberUserDO,1,"");

		return R.ok();
	}

	private void findUpUserAndSaveOrderCom(String orderId, String goodsId, String productId, Integer num, int dqlevel, MemberUserDO upUser, BigDecimal price) {
		//获取出接单价(出返利)的人,也就是上级吃返利的人,
		Map<String,Object> vipMap = new HashMap<>();
		vipMap.put("level", dqlevel);
		vipMap.put("userId", upUser.getId());
		List<MemberUserDO> myUpVip = memberUserDao.getMyUpVip(vipMap);

		if(myUpVip!=null&&myUpVip.size()>0){
			saveOrderCom(orderId, price, goodsId, productId, num, upUser,myUpVip.get(0).getId());
		}else{
			saveOrderCom(orderId, price, goodsId, productId, num, upUser,"0");
		}
	}


	/***
	 * //
	 * @param orderOrderDO  订单
	 * @param memberUserDO  用户
	 * @param actionType 默认1:支付成功,2:支付失败,3:用户取消,4:超时未支付;5:商家取消;10:其他原因取消
	 * @param actionRemark  // action_type=10时填上具体原因
	 */
	public void syncShopOrderPay(OrderOrderDO orderOrderDO, MemberUserDO memberUserDO,int actionType,String actionRemark) {
		//同步视频号订单结果
		try {
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
			WxMaShopOrderService wxMaShopOrderService = new WxMaShopOrderServiceImpl(wxService);
			WxMaShopOrderPayRequest wxMaShopOrderPayRequest = new WxMaShopOrderPayRequest();
			wxMaShopOrderPayRequest.setOutOrderId(orderOrderDO.getId());
			wxMaShopOrderPayRequest.setActionRemark(actionRemark);
			wxMaShopOrderPayRequest.setActionType(actionType);
			wxMaShopOrderPayRequest.setOpenid(memberUserDO.getWechatOpenId());
			wxMaShopOrderPayRequest.setPayTime(DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN));   // action_type=1时必填  支付时间
			wxMaShopOrderPayRequest.setTransactionId(orderOrderDO.getPayNum());  // // action_type=1时必填  支付交易号/订单号
			WxMaShopBaseResponse wxMaShopBaseResponse = wxMaShopOrderService.orderPay(wxMaShopOrderPayRequest);
			System.out.println(wxMaShopBaseResponse.toString());
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
	}

	private void saveOrderTeamOrder(String orderId, OrderOrderDO orderOrderDO, MemberUserDO upUser) {
		OrderTeamMoneyDO orderTeamMoneyDO = new OrderTeamMoneyDO();
		orderTeamMoneyDO.setOrderId(orderId);
		orderTeamMoneyDO.setCaAt(new Date());
		orderTeamMoneyDO.setId(IdUtil.simpleUUID());
		orderTeamMoneyDO.setUserId(upUser.getId());
		orderTeamMoneyDO.setDelFlag(0);

		switch (upUser.getLevel()) {
			case 0:
				orderTeamMoneyDO.setMoney(orderOrderDO.getPayment());
				break;
			case 1:
				orderTeamMoneyDO.setMoney(orderOrderDO.getPaymentC());
				break;
			case 2:
				orderTeamMoneyDO.setMoney(orderOrderDO.getPaymentZ());
				break;
			case 3:
				orderTeamMoneyDO.setMoney(orderOrderDO.getPaymentG());
				break;
			default:
				orderTeamMoneyDO.setMoney(new BigDecimal("0.00"));
		}

		orderTeamMoneyDao.save(orderTeamMoneyDO);
	}

	/**
	 *
	 * @param orderId 订单id
	 * @param price  返利金额
	 * @param goodsId  商品id
	 * @param productId  产品id
	 * @param num  数量
	 * @param upUser  吃返利用户
	 */
	private void saveOrderCom(String orderId, BigDecimal price, String goodsId, String productId, Integer num, MemberUserDO upUser,String comUser) {
		OrderComDO orderComDO = new OrderComDO();
		orderComDO.setStatus(0);
		orderComDO.setComPrice(price);
		orderComDO.setOrderId(orderId);
		orderComDO.setId(IdUtil.simpleUUID());
		orderComDO.setCreateAt(new Date());
		orderComDO.setDelFlag(0);
		orderComDO.setGoodsId(goodsId);
		orderComDO.setNum(num);
		if(!"-1".equals(comUser)){
			orderComDO.setComUser(comUser);
		}

		orderComDO.setProductId(productId);
		orderComDO.setUserId(upUser.getId());
		orderComDao.save(orderComDO);
	}

	@Override
	public Map<String, Object> getTeamOrder(Map<String, Object> map) {
		String userId = map.get("userId").toString();
		String orderId = map.get("orderId").toString();
		MemberUserDO memberUserDO = memberUserDao.get(userId);
		int level = 0;
		if (memberUserDO != null) {
			map.put("level", memberUserDO.getLevel());
			level = memberUserDO.getLevel();
		} else {
			map.put("level", 0);
			level = 0;
		}
		Map<String, Object> orderMap = orderOrderDao.getTeamOrder(map);
		if (orderMap == null) {
			return R.error(1, "该商品暂时不能拼团");
		}
		List<Map<String, Object>> userList = orderTeamUserDao.getUserByOrder(map);
		orderMap.put("userList", userList);
		return R.ok().put("data", orderMap);

	}

	/**
	 * 自动收货
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void receivingOrderJob() {
		int value = orderSetDao.list(new HashMap<String, Object>()).get(0).getValue();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date aa = DateUtils.subDayOfDate(date, value);
		String day = format.format(aa);// 几天前的时间
		List<OrderOrderDO> orderList = orderOrderDao.receivingOrderJob(day);
		if (orderList.size() > 0) {
			for (OrderOrderDO order : orderList) {
				MemberUserDO userDO = memberUserDao.get(order.getUserId());
				List<Map<String, Object>> byOrderId = orderDetailDao.getByOrderId(order.getId());
				GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(byOrderId.get(0).get("goodId").toString());
				int total = MapUtil.getInt(byOrderId.get(0),"total");
				if (order.getStatus() == 4) {
					order.setStatus(7);
					order.setEndAt(date);
					order.setUpdateAt(date);
					orderOrderDao.update(order);


					// 订单完成后返佣到账
					updateCmsAndScore(date, order);

					ShopExpressCodeDO shopExpressCodeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
					receivingMessage(order, userDO, goodsGoodsDO, total, order, shopExpressCodeDO,0);


					//往平台公告表加入数据
					CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
					cmsNoticeDO.setId(IdUtil.simpleUUID());
					cmsNoticeDO.setContent("您订单号为:"+order.getOrderSn()+"的订单自动收货成功!收货时间:"+DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN)+",如需帮助,请联系客服!");
					cmsNoticeDO.setDelFlag(0);
					cmsNoticeDO.setCaAt(new Date());
					cmsNoticeDO.setTitle("订单自动收货通知");
					cmsNoticeDO.setUserId(order.getUserId());
					cmsNoticeDao.save(cmsNoticeDO);
					//同步视频号订单收货
					//
					// syncRecieveOrder(order);


					//MemberUserDO memberUserDO = memberUserDao.get(order.getUserId());
					/*// 减库存和升级
					updateUserLevel(order.getUserId(), order.getId(), memberUserDO);*/
				} else if (order.getStatus() == 1) {
					order.setStatus(8);
					order.setUpdateAt(date);
					order.setBuyerMsg("自动取消");
					orderOrderDao.update(order);
					// 删除返利的佣金
					orderComDao.removeCom(order.getId());
					//返还优惠券
					if(StringUtils.isNoneBlank(order.getCouponId())){
						MemberCouponDO memberCouponDO = memberCouponDao.get(order.getCouponId());
						if(memberCouponDO!=null){
							SalesCouponDO salesCouponDO = salesCouponDao.get(memberCouponDO.getCouponId());
							if(salesCouponDO.getLimitEndat().after(new Date())){
								memberCouponDO.setStatus(2);
							}else{
								memberCouponDO.setStatus(0);
							}
							memberCouponDao.update(memberCouponDO);
						}
					}

					//发送订阅消息
					cancelMesage(order, userDO, goodsGoodsDO, total, 1);

					//往平台公告表加入数据
					CmsNoticeDO cmsNoticeDO = new CmsNoticeDO();
					cmsNoticeDO.setId(IdUtil.simpleUUID());
					cmsNoticeDO.setContent("您订单号为:"+order.getOrderSn()+"的订单已超时自动!取消时间:"+DateUtil.format(new Date(),DateUtils.DATE_TIME_PATTERN)+",如需帮助,请联系客服");
					cmsNoticeDO.setDelFlag(0);
					cmsNoticeDO.setCaAt(new Date());
					cmsNoticeDO.setTitle("订单超时取消通知");
					cmsNoticeDO.setUserId(order.getUserId());
					cmsNoticeDao.save(cmsNoticeDO);

					//同步视频号订单取消
					//MemberUserDO memberUserDO = memberUserDao.get(order.getUserId());
					//syncShopOrderPay(order,memberUserDO,4,"");
					/*// 删除减掉的库存
					int a = memberStockDao.removeStock(order.getId());*/
				}

			}
		}

	}

	//佣金到账
	private void updateCmsAndScore(Date date, OrderOrderDO order) {

		orderComDao.updateByOrderId(order.getId());
		List<OrderComDO> list = orderComDao.getByOrderId(order.getId());
		if(list.size()>0){
			for (OrderComDO orderComDO : list) {
				MemberPriceDO memberPriceDO = new MemberPriceDO();
				memberPriceDO.setDelFlag(0);
				memberPriceDO.setPrice(orderComDO.getComPrice());
				memberPriceDO.setId(UuidUtil.get32UUID());
				memberPriceDO.setStatus(3);
				memberPriceDO.setCreateAt(new Date());
				memberPriceDO.setType(3);
				memberPriceDO.setGId(order.getId());
				memberPriceDO.setUserId(orderComDO.getUserId());
				memberPriceDao.save(memberPriceDO);
			}
		}



	}

	@Override
	public int countUserAndProductId(Map<String, Object> canMap) {
		// TODO Auto-generated method stub
		return orderOrderDao.countUserAndProductId(canMap);
	}

	@Override
	public List<OrderOrderDO> getByPayNum(String payNum) {
		List<OrderOrderDO> list = orderOrderDao.getByPayNum(payNum);
		return list;
	}

    @Override
    public Map<String, Object> getOrderDetails(Map<String, Object> params) {
		Map<String, Object>  map= orderOrderDao.getOrderDetails(params);
		return map;
    }


	/*后台换货列表*/
	@Override
	public List<Map<String,Object>> getModifyOrderList(Map<String, Object> map){
		return orderOrderDao.getModifyOrderList(map);
	}

	/**
	 * 添加换货申请
	 * @param paramMap
	 * @return
	 */
	@Override
	public int addModify(Map<String, Object> paramMap) {
		paramMap.put("id",UuidUtil.get32UUID());
		paramMap.put("status",0);
		paramMap.put("delFlag",0);
		paramMap.put("createAt",new Date());
		paramMap.put("updateAt",new Date());
		return orderOrderDao.addModify(paramMap);
	}

	/*后台换货同意并修改物流*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R modifyOrderT(Map<String, Object> params) {
		String orderId = params.get("orderId").toString();
		/*String tableName = params.get("tableName").toString();*/
		String [] datail = params.get("datail").toString().split(",");   //物流信息，物流名代号,物流单号

		OrderOrderDO order = new OrderOrderDO();
		order.setId(orderId);
		order.setShippingName(datail[0].split(":")[0]);
		order.setShippingCode(datail[0].split(":")[1]);
		order.setStatus(4);
		/*order.setTableName(tableName);*/
		orderOrderDao.update(order);
		//修改换货订单状态
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("orderId", orderId);
		map.put("status", 1);
		orderModifyDao.editStatusByOrderId(map);
		//orderModifyDao.editStatusByOrderId(map);

		//删除原先的物流信息
		shopExpressMessageDao.removeByOrderId(orderId);
		shopExpressDetailsDao.removeByOrderId(orderId);
		//添加新的物流信息
		for (int i=0; i<datail.length; i++) {
			String[] shop = datail[i].toString().split(":");
			String code = shop[0];
			String expressId = shop[1];
			ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(code);
			String name = codeDO.getName();
			String userId = orderOrderDao.get(orderId).getUserId();
			ShopExpressMessageDO messageDO = new ShopExpressMessageDO();
			messageDO.setId(UuidUtil.get32UUID());
			messageDO.setStatus(0);
			messageDO.setName(name);
			messageDO.setCode(code);
			messageDO.setExpressId(expressId);
			messageDO.setUserId(userId);
			messageDO.setDelFlag(Constant.DEFAULT_DEL_FLAG);
			messageDO.setOpAt(new Date());
			messageDO.setOrderId(orderId);
			shopExpressMessageDao.save(messageDO);
		}
		return R.ok();
	}

	/*后台换货驳回*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R modifyOrderF(OrderOrderDO order) {
		orderOrderDao.update(order);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("orderId",order.getId());
		map.put("status",2);
		orderModifyDao.editStatusByOrderId(map);
		return R.ok();
	}

	@Override
	public Map<String, Object> getOrderByType(Map<String, Object> paramMap) {
		Map<String,Object> query = new HashMap<>();
		Map<String,Object> map = new HashMap<>();
		if("0".equals(paramMap.get("type").toString())){
			query.put("orderId",paramMap.get("orderId"));
			map = orderDetailDao.backList(query);
		}else if("1".equals(paramMap.get("type").toString())){
			query.put("orderId",paramMap.get("orderId"));
			map = orderDetailDao.modifyList(query);
		}
		return map;
	}

	@Override
	public BigDecimal onceUseMoney(Map<String, Object> map) {
		return orderOrderDao.onceUseMoney(map);
	}

	@Override
	public R addShopExpressInfo(Map<String, Object> paramMap) {
		OrderBackDO orderBackDO = orderBackDao.getByOrderId(MapUtil.getStr(paramMap, "orderId"));
		if(orderBackDO.getStatus()==0){
			return R.error("请等待商家处理完再添加快递信息");
		}else if(orderBackDO.getStatus()>1){
			return R.error("已填写过信息,不能重复填写");
		}
		if(StringUtils.isNoneBlank(MapUtil.getStr(paramMap,"phone"))){
			orderBackDO.setPhone(MapUtil.getStr(paramMap,"phone"));
		}
		orderBackDO.setStatus(2);
		orderBackDO.setExpressCode(MapUtil.getStr(paramMap,"expressCode"));
		orderBackDO.setExpressName(MapUtil.getStr(paramMap,"expressName"));
		orderBackDO.setUpdateAt(new Date());
		orderBackDO.setReturnReason(MapUtil.getStr(paramMap, "returnReason"));
		orderBackDO.setImgurl(MapUtil.getStr(paramMap, "imgurl"));
		orderBackDao.update(orderBackDO);
		return R.ok();


	}

}
